这个问题在这里已有答案:
我想用一个按钮在Python中做一些事情(使用Tkinter)。我希望按钮能够获得当前选择的组合框并将其打印在屏幕上。
图形布局是3个独立的帧,但按钮和组合框都位于同一帧(帧#2)中。
问题是我不能参考组合框。我读到的错误:
Frame object has no attribute 'box'
Window object has no attribute 'box'
self.box=ttk.Combobox(self.frame2 , values[...])
self.button1=tk.Button(self.frame2, command= self.wipe(), text=...)
def wipe(self):
self.box.get()
另外,我尝试过:
def wipe(self):
self.frame2.box.get()
目标是简单地从Combobox中获取所选择的选项。
这里是产生相同错误的最小编码:
import tkinter as tk
from tkinter import ttk
class window():
def __init__(self,root):
self.frame=tk.Frame(root)
self.key=tk.Button(self.frame,text='PRESS ME',command=self.wipe())
self.box=ttk.Combobox(self.frame, options=['1','2','3'])
self.frame.pack()
self.key.pack()
self.box.pack()
def wipe(self):
self.box.get()
master=tk.Tk()
master.geometry('400x400')
app=window(master)
master.mainloop()
我会在问题中添加标签“tkinter”。
请尝试以下方法:
def wipe(self):
# code
self.box=ttk.Combobox(self.frame2 , values[...])
self.button1=tk.Button(self.frame2, command=wipe, text=...)
请注意以下事项:
command=self.wipe()
,因为这里有两个问题。首先,您将command
设置为self.wipe()
的结果,而不是函数。其次,你没有定义self.wipe
,你定义了wipe
。command=wipe
将command
关键字参数设置为函数wipe
自从我处理tkinter以来已经很久了,如果这不起作用,我会尝试通过再次检查文档来提供帮助。