【问题标题】:Python Tk() Button command not completely workingPython Tk()按钮命令不完全工作
【发布时间】:2016-06-27 16:12:40
【问题描述】:

我对 python 编程很陌生,并且有一个我自己似乎无法解决的基本问题 - 我希望有人能够对此有所了解!

我创建了一个.py 文件,该文件在用户和(随机)计算机之间运行基本的 Rock、Paper、Scissors 游戏。这通过 tk() 使用 GUI 并且工作得非常好。

然后,我创建了另一个 .py 文件,这一次是为了创建一个整体菜单 GUI,我可以从中选择运行我的 Rock, Paper, Scissors 游戏。我可以创建这个tk() 很好,选择RPS游戏的按钮,游戏加载,但这次它根本不起作用!我可以按下按钮,但它们无法进行游戏。

这是我的game.py 代码:

from tkinter import *
from tkinter.ttk import *
import random

def gui():
    <game code goes in here, including other functions>

root=Tk()
root.title("Rock, Paper, Scissors")
# more code to define what this looks like
# including a Frame, buttons, labels, etc>

if __name__=='__main__':
    gui()

然后我创建了整个游戏菜单 menu.py:

from tkinter import *
from tkinter.ttk import *
import random
import game

main=Tk()
main.title("J's games")

mainframe=Frame(main,height=200,width=500)
mainframe.pack_propagate(0)
mainframe.pack(padx=5,pady=5)

intro=Label(mainframe,
    text="""Welcome to J's Games. Please make your (RPS) choice.""")
intro.pack(side=TOP)

rps_button=Button(mainframe, text="Rock,Paper,Scissors", command=game.gui)
rps_button.pack()

test_button=Button(mainframe,text="Test Button")
test_button.pack()

exit_button=Button(mainframe,text="Quit", command=main.destroy)
exit_button.pack(side=BOTTOM)

main.mainloop()

如果有人能看到明显的东西,请告诉我。我对它为什么独立工作感到困惑,但当我将它合并到另一个功能(按钮命令)时却没有。我已经尝试过 IDLE 调试,但它似乎冻结了我!

【问题讨论】:

  • 一个问题是您正在创建两个根窗口(即:您调用Tk() 两次)。一个 tkinter 程序应该只有一个根窗口。
  • 请在写入框中仅缩进一次代码,以便格式化后显示为左对齐,因此可以剪切和粘贴,并且可以在不进一步取消缩进的情况下运行。

标签: python user-interface button tkinter


【解决方案1】:

我假设您希望在选择特定游戏时保留主窗口。这意味着游戏应该在一个单独的框架中,最初在一个单独的顶层。修改您的 rps 文件,如下所示,

from tkinter import *
from tkinter.ttk import *
import random

class RPS(Toplevel):
    def __init__(self, parent, title):
        Toplevel.__init__(parent)
        self.title(title)
    #game code goes in here, including other functions

# more code to define what this looks like
# including a Frame, buttons, labels, etc>

if __name__=='__main__':
    root=Tk()
    root.withdraw()
    RPS(title = "Rock, Paper, Scissors")
    root.mainloop()

这样,导入文件不会创建第二个根和主循环。

如果您希望一次只运行一个游戏,您可以改用带有两个窗格的窗格窗口。 Turtledemo 就是这样做的。代码在turtledemo.ma​​in中。然后,您将从 Frame 派生 RPS 并将其打包到第二个窗格中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 2018-06-23
    相关资源
    最近更新 更多