我开始学习Python,我遇到了一个问题,我在任何教程中都没有讨论过这个问题。
基本上,当程序变得更复杂时,我已经失去了控制新元素出现位置的能力。很难为我解释,因为英语不是我的母语所以我做了一个模拟程序,显示我的主程序有什么问题。
import Tkinter as tk
import ttk as ttk
clutter=['1PLACEHOLDER', '2PLACEHOLDER', '3PLACEHOLDER', 'PICK ME']
class GRAPHIC_INTERFACE(tk.Frame):
def __init__(self,*args):
tk.Frame.__init__(self, *args)
self.grid()
self.first_window()
def first_window(self):
self.button1=tk.Button(self, text="PLACEHOLDER")
self.button1.grid()
self.button2=tk.Button(self, text="CLICK ME", command=self.second_window)
self.button2.grid()
self.button3=tk.Button(self, text="PLACEHOLDER")
self.button3.grid()
#the additional button apears here
def second_window(self):
alpha=tk.Toplevel(self)
self.button4=tk.Button(alpha, text="PLACEHOLDER")
self.button4.grid()
self.button5=tk.Button(alpha, text="CLICK ME", command= self.third_window)
self.button5.grid()
def third_window(self):
beta=tk.Toplevel(self)
self.BOXXY=ttk.Combobox(beta, values= clutter, state='readonly')
self.BOXXY.bind("<<ComboboxSelected>>", self.misplaced_button) #after choosing the third option an aditional button is created
self.BOXXY.current(0)
self.BOXXY.grid()
self.button6=tk.Button(beta, text="PLACEHOLDER")
self.button6.grid()
#the additional button needs to appear here
def misplaced_button(self, *args):
Catie=self.BOXXY.get()
if Catie=='PICK ME':
self.button7=tk.Button(self, text="I am that problematic button")#this button needs to be in the third window
self.button7.grid()
else:
print "that was not the chosen one"
root=tk.Tk()
root.title("Mockup")
root.geometry("180x200")
app=GRAPHIC_INTERFACE(root)
root.mainloop()
起初我以为我可以通过给它们命名(即alpha,beta)来控制小部件的位置,但显然我错了。
答案 0 :(得分:0)
如果self.button7
应该在第三个窗口中,那么您所要做的就是使用第三个窗口作为按钮的父级。
您可以通过以下多种方式完成:您可以将窗口保存为属性,可以在调用函数时传递窗口,也可以根据哪个寡妇捕获事件来计算窗口。
这是一个将按钮置于获取事件的顶层中的解决方案:
def misplaced_button(self, event):
...
toplevel = event.widget.winfo_toplevel()
self.button7=tk.Button(toplevel,...)
...