gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:56:50 25 4
gpt4 key购买 nike

我正在为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com