如何运行会影响变量且不会破坏代码的while循环?

时间:2018-09-12 13:49:55

标签: python python-3.x variables tkinter while-loop

我试图运行一个while循环,以更改代码中的变量,但只会破坏代码。我不确定该怎么办。我希望在不重复命令的情况下更改T时更改X。

import tkinter
from tkinter import *

code = Tk()

T = 1
X = 0



def printx():
    global X
    print(X);
def teez():
    global T
    T = 0;
def teeo():
    global T
    T = 1;

while T == 1:
    X = 5
else:
    X = 6

button1 = Button(code, text = "Print X", command = printx)
button1.pack()
button2 = Button(code, text = "T = 0", command = teez)
button2.pack()
button2 = Button(code, text = "T = 1", command = teeo)
button2.pack()

code.mainloop()

P.S。它在python 3.7中

1 个答案:

答案 0 :(得分:1)

首先让我们更正您的导入。

您不需要两次导入Tkinter,最好不要使用*

导入Tkinter的最佳方法如下:

import tkinter as tk

然后只需为Tkinter小部件使用tk.前缀即可。

现在解决循环问题。 Tkinter带有一个很酷的方法after()。请记住,after()方法使用数字表示毫秒,因此1000为1秒。因此,在下面的代码中,我们每秒运行check_t函数1000次。您可能希望根据需要进行更改。我们可以使用此方法和函数来检查变量的状态并进行所需的更改,而不会像mainloop()语句那样影响while

import tkinter as tk

root = tk.Tk()

T = 1
X = 0

def printx():
    global X
    print(X)

def teez():
    global T
    T = 0

def teeo():
    global T
    T = 1
def check_t():
    global T, X
    if T == 1:
        X = 5
        root.after(1, check_t)
    else:
        X = 6
        root.after(1, check_t)

button1 = tk.Button(root, text = "Print X", command = printx)
button1.pack()
button2 = tk.Button(root, text = "T = 0", command = teez)
button2.pack()
button2 = tk.Button(root, text = "T = 1", command = teeo)
button2.pack()

check_t()

root.mainloop()

上面的代码将完全执行您要执行的操作,而不会冻结mainloop()。也就是说,我真的不喜欢使用很多全局语​​句,而是更喜欢OOP路线。以下代码是OOP中代码的重做版本。

import tkinter as tk

class MyApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.t = 1 # changed to lower case name as UPPER case is used for constants
        self.x = 0
        tk.Button(self, text="Print X", command=self.printx).pack()
        tk.Button(self, text="T = 0", command=self.teez).pack()
        tk.Button(self, text="T = 1", command=self.teeo).pack()
        self.check_t()

    def printx(self):
        print(self.x)

    def teez(self):
        self.t = 0

    def teeo(self):
        self.t = 1

    def check_t(self):
        if self.t == 1:
            self.x = 5
            self.after(1, self.check_t)
        else:
            self.x = 6
            self.after(1, self.check_t)

MyApp().mainloop()