简体   繁体   English

Python:使用Tkinter(ttk)构建简单表单

[英]Python: Using Tkinter(ttk) to build a simple form

What am I doing wrong here? 我在这里做错了什么? I would like to get my input value in a variable. 我想在一个变量中获取输入值。 When I finish with the input, I will print the variable to the console. 完成输入后,我会将变量输出到控制台。 Here's my code: 这是我的代码:

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()

What am I doing wrong here? 我在这里做错了什么?

You stopped in the middle of writing your code and didn't finish: 您在编写代码的过程中停了下来,但是没有完成:

button1 = tk.Button(self, text="Get", command=self.on_button

Not only did you not finish this line, you didn't define on_button . 您不仅没有完成这一行,而且没有定义on_button Other issues include: self undefined; 其他问题包括: self不确定; button1 gets initialized to two different buttons; button1被初始化为两个不同的按钮; and you're expecting inline code to respond to an event. 并且您期望内联代码能够响应事件。

Your program starts out fine but then takes a turn towards random bits of pasted code that don't hang together. 您的程序一开始就很好,但是随后转向了无法粘贴在一起的随机粘贴代码。 I would have expected something like: 我本来希望这样的:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM