如何使tkinter小部件具有全局性



我正在制作一个python程序,该程序有多个Tkinter GUI,其中一个GUI是在函数内部定义的,我想访问函数外部的Tkinter(在函数中定义(元素,我该如何做到这一点?

python版本:3.9(Conda(

代码示例:

from tkinter import *
firstGUI = TK()
testBox = Text(firstGUI)
bt = Button(firstGUI,text="Launch the second gui",command=test)
firstGUI.mainloop()
def putText():
sample = testBox.get()
testBox2.insert('1.0',sample) #how i can access the testbox2 here    
def test():
secondGUI = Toplevel()
testBox2 = Text(firstGUI)
button = (secondGUI,text="SEND",command=putText)
secondGUI.mainloop()

提前感谢!

所以我知道您可能是新手,但您的代码有很多问题。

  • 首先:始终在脚本的开头定义函数
  • 第二:尽量避免*imports,将使用import-tkinter作为tk
  • 第三:你创建了小部件(文本、按钮(,但你没有把它们放在你的窗口小部件。我使用grid完成了此操作

下面是一个我认为你想要实现的目标的例子。如果你考虑到这些,你就不需要做任何全球性的事情。我建议您观看更多基本的tkinter/python教程。祝你好运

import tkinter as tk

def putText():
txt = "Hello Worldn"
testBox.insert('end', txt)  # how i can access the testbox2 here

def test():
secondGUI = tk.Toplevel()
button = tk.Button(secondGUI, text='SEND', command=putText)
button.grid(row=0, column=0)
secondGUI.mainloop()

firstGUI = tk.Tk()
testBox = tk.Text(firstGUI)
testBox.grid(row=1, column=1)
bt = tk.Button(firstGUI, text="Launch the second gui", command=test)
bt.grid(row=0, column=0)
firstGUI.mainloop()

最新更新