【问题标题】:How do I run a while loop that affects my variables and doesn't break my code? [closed]如何运行影响我的变量并且不会破坏我的代码的 while 循环? [关闭]
【发布时间】:2019-02-17 04:34:17
【问题描述】:

我正在尝试运行一个 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()

附:它在 python 3.7 中

【问题讨论】:

  • 它破坏你的代码的原因是它是一个无限循环。我不确定你想做什么。
  • 你还需要在你的while循环中有一个if...else。也插入一个 break 语句
  • @khelwood 我希望它在我更改 T 时更改 x 但我不希望它在函数内部。
  • 我会后退一步,问你为什么不想在函数内部更改 X?编写的 while 循环永远不会让您的代码到达 tkinter 按钮定义。
  • 我认为您正在尝试执行 if 语句。如果您能告诉我们您想通过 while 循环实现什么目标,我们可以帮助您解决问题

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


【解决方案1】:

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

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

导入 Tkinter 的最佳方式是这样的:

import tkinter as tk

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

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

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2018-03-21
    • 1970-01-01
    • 2013-02-17
    • 2021-03-12
    • 1970-01-01
    相关资源
    最近更新 更多