我在这里做错了什么?我想在一个变量中获取输入值。完成输入后,我会将变量输出到控制台。这是我的代码:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
w = tk.Frame(root)
w.grid(row=0, columnspan=3)
first_label = tk.Label(w, text="myEntry: ")
myEntry = tk.StringVar()
myEntry_entry = ttk.Entry(w, textvariable= myEntry)
first_label.grid(row=0, column=0, padx=10, sticky=tk.W)
myEntry_entry.grid(row=0, column=1, sticky=tk.W, padx=10)
button1 = tk.Button(w, text='Print in Console')
button1.grid(row=4, columnspan=1, sticky=tk.W)
button1 = tk.Button(self, text="Get", command=self.on_button
myValue = myEntry.get()
print(myValue)
root.mainloop()
答案 0 :(得分:2)
我在这里做什么错了?
您在编写代码的过程中停了下来,但是没有完成:
button1 = tk.Button(self, text="Get", command=self.on_button
您不仅没有完成这一行,而且没有定义on_button
。其他问题包括:self
未定义; button1
被初始化为两个不同的按钮;并且您期望内联代码能够响应事件。
您的程序起步很好,但随后转向了不会挂在一起的随机粘贴的代码位。我本来希望像这样:
import tkinter as tk
from tkinter import ttk
def on_button():
myValue = myEntry.get()
print(myValue)
root = tk.Tk()
w = tk.Frame(root)
w.grid(row=0, columnspan=3)
first_label = tk.Label(w, text="myEntry: ")
first_label.grid(row=0, column=0, padx=10, sticky=tk.W)
myEntry = tk.StringVar()
myEntry_entry = ttk.Entry(w, textvariable=myEntry)
myEntry_entry.grid(row=0, column=1, sticky=tk.W, padx=10)
button1 = tk.Button(w, text="Print in Console", command=on_button)
button1.grid(row=4, columnspan=1, sticky=tk.W)
root.mainloop()