Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

python - Tkinter: Calling function when button is pressed

import tkinter as tk

def load(event):
    file = open(textField.GetValue())
    txt.SetValue(file.read())
    file.close()

def save(event):
    file = open(textField.GetValue(), 'w')
    file.write(txt.GetValue())
    file.close()


win = tk.Tk() 
win.title('Text Editor')
win.geometry('500x500') 

# create text field
textField = tk.Entry(win, width = 50)
textField.pack(fill = tk.NONE, side = tk.TOP)

# create button to open file
openBtn = tk.Button(win, text = 'Open', command = load())
openBtn.pack(expand = tk.FALSE, fill = tk.X, side = tk.TOP)

# create button to save file
saveBtn = tk.Button(win, text = 'Save', command = save())
saveBtn.pack(expand = tk.FALSE, fill = tk.X, side = tk.TOP)

I get the error that load and save are missing a position argument: event. I understand the error, but don't understand how to resolve it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a runnable answer. In addition to changing the commmand= keyword argument so it doesn't call the function when the tk.Buttons are created, I also removed the event argument from the corresponding function definitions since tkinter doesn't pass any arguments to widget command functions (and your function don't need it, anyway).

You seem to be confusing event handlers with widget command function handlers. The former do have an event argument passed to them when they're called, but the latter typically don't (unless you do additional stuff to make it happen—it's a fairly common thing to need/want to do and is sometimes referred to as theThe?extra?arguments?trick).

import tkinter as tk

# added only to define required global variable "txt"
class Txt(object):
    def SetValue(data): pass
    def GetValue(): pass
txt = Txt()
####

def load():
    with open(textField.get()) as file:
        txt.SetValue(file.read())

def save():
    with open(textField.get(), 'w') as file:
        file.write(txt.GetValue())

win = tk.Tk()
win.title('Text Editor')
win.geometry('500x500')

# create text field
textField = tk.Entry(win, width=50)
textField.pack(fill=tk.NONE, side=tk.TOP)

# create button to open file
openBtn = tk.Button(win, text='Open', command=load)
openBtn.pack(expand=tk.FALSE, fill=tk.X, side=tk.TOP)

# create button to save file
saveBtn = tk.Button(win, text='Save', command=save)
saveBtn.pack(expand=tk.FALSE, fill=tk.X, side=tk.TOP)

win.mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...