python - 为猜数字游戏创建重置按钮

标签 python tkinter

我正在为 Python 教程制作一个猜数字游戏。我是 Python 新手,正在使用 Python Shell 和版本 2.7.5。除了这个以外的所有功能我都做了。

我必须制作一个重置按钮,这让我很困惑。我不知道如何定义它。

self.reset_bttn = Button(self, text = "Starta om", command=reset)
        self.reset_bttn.grid(row = 6, column = 1, sticky = W)

def reset():
        global

这是带有一些标签的代码的开头。

from Tkinter import *
import random
number = random.randrange (100) + 1
tries = 0
class Application(Frame):

    def __init__(self, master):

        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()


    def create_widgets(self):

        self.inst_lbl = Label(self, text = "Följ alla stegen")
        self.inst_lbl.grid(row = 0, column = 0, columnspan = 2, sticky = W)

        self.name_lbl = Label(self, text = "Spelarens namn: ")
        self.name_lbl.grid(row = 1, column = 0, sticky = W)

        self.name_ent = Entry(self)
        self.name_ent.grid(row = 1, column = 1, sticky = W)

        self.guess_lbl = Label(self, text = "Skriv in din gissning.")
        self.guess_lbl.grid(row = 2, column = 0, sticky = W)

        self.guess_ent = Entry(self)
        self.guess_ent.grid(row = 2, column = 1, sticky = W)

        self.gap1_lbl = Label(self, text = " ")
        self.gap1_lbl.grid(row = 3, column = 0, sticky = W)

最佳答案

您可能需要将以下内容添加到您的应用程序类中:

class Application(Frame):
    # ... all the stuff you've copied in your question
    def create_widgets(self):
        # ... all the stuff again
        self.reset_bttn = Button(self, text = "Starta om", command=self.reset)

    def reset(self):
        self.name_ent.delete(0, tk.END)
        self.guess_ent.delete(0, tk.END)
        # ... more stuff to be reset here

我没有对此进行测试,也从未做过tkinter(至少据我记得),但我刚刚阅读了 documentation ! ;-)

.delete(first, last=None) Deletes characters from the widget, starting with the one at index first, up to but not including the character at position last. If the second argument is omitted, only the single character at position first is deleted.

和:

Positions within the widget's displayed text are given as an index. There are several ways to specify an index:

  • As normal Python indexes, starting from 0.
  • The constant tk.END refers to the position after the existing text.

哦,我觉得有必要补充一点,你应该永远不要使用全局变量。没有充分的理由或情况来使用它们。除非您想编写难以阅读和维护的丑陋代码。

您应该将这些全局变量作为成员推送到类内部。

关于python - 为猜数字游戏创建重置按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17091388/

相关文章:

python - 销毁动态创建的小部件

Python:如何从 pandas 列中删除所有非数字值?

python - 在 Python 3.5.2 中使用 tkinter 更新按钮按下时输入字段中的标签

python - Seaborn - 从 DataFrame 直方图中删除间距

python - 停止主管不会停止 celery worker

python-2.7 - 滚动文本 "spill over"顶部边框内的复选按钮

python - tkinter 设置比例(创建 2x2 框)

python - python中的碰撞检测算法

python - 将由不同形状的 numpy 数组组成的 numpy 数组保存到 .txt 文件

python - pandas.DataFrame.drop 掉落了错误的标签