Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Tkinter:为什么;1.结束“;“工作但不工作”;2.0“;?_Python_Multithreading_Tkinter - Fatal编程技术网

Python Tkinter:为什么;1.结束“;“工作但不工作”;2.0“;?

Python Tkinter:为什么;1.结束“;“工作但不工作”;2.0“;?,python,multithreading,tkinter,Python,Multithreading,Tkinter,我使用Tkinter编写了以下Python 3代码: from tkinter import * import threading import time class Foo: def replace(self): time.sleep(1) self.text_field.replace("1.end", END, "\n" + "New Line 2") def create_gui(self): self.window =

我使用Tkinter编写了以下Python 3代码:

from tkinter import *
import threading
import time

class Foo:
    def replace(self):
        time.sleep(1)
        self.text_field.replace("1.end", END, "\n" + "New Line 2")
    def create_gui(self):
        self.window = Tk()
        self.text_field = Text(height = 30, width = 70)
        self.text_field.pack()
        self.text_field.insert(END, "Line 1" + "\n" + "Line 2" + "\n" + "Line 3")

        self.window.mainloop()

if __name__ == "__main__":
    foo_object = Foo()
    threading.Thread(target = foo_object.replace, daemon = True).start()
    foo_object.create_gui()
在这个版本的代码中,一切都按预期工作;此时会出现一个窗口,其中包含一个文本字段,显示

Line 1
Line 2
Line 3
一秒钟后,它变成了

Line 1
New Line 2
但是,如果我将第8行中的
“1.end”
更改为
“2.0”
,则代码无法正常工作。在原始窗口出现在我的屏幕上大约2秒钟后,它会自动关闭,而不会替换文本

新代码:

from tkinter import *
import threading
import time

class Foo:
    def replace(self):
        time.sleep(1)
        self.text_field.replace("2.0", END, "\n" + "New Line 2")
    def create_gui(self):
        self.window = Tk()
        self.text_field = Text(height = 30, width = 70)
        self.text_field.pack()
        self.text_field.insert(END, "Line 1" + "\n" + "Line 2" + "\n" + "Line 3")

        self.window.mainloop()

if __name__ == "__main__":
    foo_object = Foo()
    threading.Thread(target = foo_object.replace, daemon = True).start()
    foo_object.create_gui()
我认为调用
self.text\u field.replace(“2.0”,END,“\n”+“New Line 2”)
只会将第二行开始之后的所有文本替换为新文本(
“\n”+“New Line 2”
),但事实并非如此。它的行为与使用
self.text\u field.replace(“1.end”,end,“\n”+“New Line 2”)
时完全不同,后者工作正常

为什么我的第二个代码示例(使用
“2.0”
)的行为是这样的


注意:只有在从不同线程调用Foo的replace()函数时才会出现此问题。

答案可能是“因为tkinter不是线程安全的”。有些版本是,但我不确定是否有任何方法可以判断您的版本是或不是,除非您专门编译了带有线程支持的tcl/tk库。另外,重要的是要知道
1.end
2.0
指的是小部件中的不同位置。@BryanOakley是的,它们指的是小部件中的不同位置,但它们在我的代码中应该完成相同的任务。我仍然不明白为什么
1.end
起作用,而
2.0
;我认为两者都可以工作,或者两者都不能工作。如果是线程问题,行为可能会有点不确定性。