我正在创建一个在输入信息时具有两种不同类型的GUI。一个是复选框,另一个是输入字段。我想让显示按钮同时显示两个输入,但是我似乎无法使它在一个按钮中工作。我可以更改它以显示一个或另一个。我不确定我要怎么做才能使两个输入都从同一个按钮显示。这是我的代码。现在,它将显示输入字段信息,而不是复选框
import tkinter as tk
from tkinter import *
def show_entry_fields():
print("First Name: %s\nLast Name: %s\nPhone Number: %s"% (e1.get(),e2.get(), e3.get()))
master = tk.Tk()
master.title("Personal Info")
Label(master, text="Your gender:").grid(row=0,column=0, sticky=W)
var1 = IntVar()
Checkbutton(master, text="male", variable=var1).grid(row=0, column=1, sticky=W)
var2 = IntVar()
Checkbutton(master, text="female", variable=var2).grid(row=0, column = 2, sticky=W)
tk.Label(master, text="First Name").grid(row=1, pady=3)
tk.Label(master, text="Last Name").grid(row=2, pady=3)
tk.Label(master, text="Phone Number").grid(row=3, pady=3)
e1 = tk.Entry(master)
e2 = tk.Entry(master)
e3 = tk.Entry(master)
e1.grid(row=1, column=1, pady=3)
e2.grid(row=2, column=1, pady=3)
e3.grid(row=3, column=1, pady=3)
tk.Button(master, text='Quit', fg="red", command=master.quit).grid(row=4,column=0, sticky=tk.E, pady=10)
tk.Button(master, text='Show', fg="blue", command=show_entry_fields).grid(row=4, column=1, sticky=tk.W, padx=50, pady=10)
tk.mainloop()
答案 0 :(得分:0)
如果您只想获得一个输出(男性或女性),这是此处使用性别输入的逻辑。那么您必须使用RadioButton
而不是CheckButton
所以您的代码将是这样:
import tkinter as tk
from tkinter import *
def show_entry_fields():
print("First Name: %s\nLast Name: %s\nPhone Number: %s\n gender: %s"% (e1.get(),e2.get(), e3.get(), var1.get()))
master = tk.Tk()
master.title("Personal Info")
Label(master, text="Your gender:").grid(row=0,column=0, sticky=W)
var1 = StringVar()
Radiobutton(master, text="male", variable=var1, value="male").grid(row=0, column=1, sticky=W)
Radiobutton(master, text="female", variable=var1, value="female").grid(row=0, column = 2, sticky=W)
tk.Label(master, text="First Name").grid(row=1, pady=3)
tk.Label(master, text="Last Name").grid(row=2, pady=3)
tk.Label(master, text="Phone Number").grid(row=3, pady=3)
e1 = tk.Entry(master)
e2 = tk.Entry(master)
e3 = tk.Entry(master)
e1.grid(row=1, column=1, pady=3)
e2.grid(row=2, column=1, pady=3)
e3.grid(row=3, column=1, pady=3)
tk.Button(master, text='Quit', fg="red", command=master.quit).grid(row=4,column=0, sticky=tk.E, pady=10)
tk.Button(master, text='Show', fg="blue", command=show_entry_fields).grid(row=4, column=1, sticky=tk.W, padx=50, pady=10)
tk.mainloop()
但是,假设您有一个选项列表,例如首选语言,并且想要获取用户选择的确切内容的输出。在这种情况下,您应该使用ListBox
关于ListBox
here