Python 如何使用entry widget和其他tkinter工具?

Python 如何使用entry widget和其他tkinter工具?,python,tkinter,Python,Tkinter,我想做的三件事是: •将GUI中显示为“!replace!”的标签小部件(代码中称为占位符)替换为条目小部件。当按下“新游戏”按钮时,新游戏中的初始球数应为输入小部件中的数字 •当剩余球数少于三个时,关闭可能导致非法移动的按钮 •使用状态标签(代码中的状态标签)向玩家提供更多反馈。删除将信息打印到pythonshell的代码,改为使用状态标签来显示信息,例如计算机拿了多少球、赢/输状态(“youwin!”或“computerwins!”)等 #注意:如果您想使用其他tkinter小部件,您需要将

我想做的三件事是:

•将GUI中显示为“!replace!”的标签小部件(代码中称为占位符)替换为条目小部件。当按下“新游戏”按钮时,新游戏中的初始球数应为输入小部件中的数字

•当剩余球数少于三个时,关闭可能导致非法移动的按钮

•使用状态标签(代码中的状态标签)向玩家提供更多反馈。删除将信息打印到pythonshell的代码,改为使用状态标签来显示信息,例如计算机拿了多少球、赢/输状态(“youwin!”或“computerwins!”)等

#注意:如果您想使用其他tkinter小部件,您需要将它们的名称添加到
#下面是导入列表
从tkinter导入Tk、画布、框架、按钮、标签、条目、结束、左、右、凹陷
从时间上导入睡眠
随机输入
#要运行此代码,请加载到Python中,并执行runNim(n),其中n是所需的初始数
#在Python shell中,包含多个球
#
#这个类就像HW6Q2的解决方案,有三个与GUI相关的小变化。
#请参见以###开头的注释。
类NimGame():
定义初始值(自身,球数):
self.numberOfBalls维护=numberOfBalls
打印(“用{}个球初始化的Nim游戏。”.format(self.numberOfBallsRemaining))
def剩余球(自身):
返回自我编号BallsRemaining
def取数(自身、球数):
如果(numberOfBalls<1)或(numberOfBalls>3)或(numberOfBalls>self.numberOfBalls保持):
打印(“你不能接受那么多球,再试一次。”)
###更新GUI中的statusLabel,告诉用户他们不能接受那么多球。
#对于家庭作业,您将停用允许此类选择的按钮,
#因此,整个“如果”将不再使用/必要。
statusLabel.configure(text=“您不能接受那个数量的球。请重试。”)
其他:
self.numberOfBallsRemaining=self.numberOfBallsRemaining-numberOfBalls
打印(“您接受了{}个球。{}个保留。”.format(numberOfBalls,self.numberOfBallsRemaining))
如果self.numberOfBallsRemaining==0:
打印(“你赢了!”)
其他:
###移除玩家选择的球后,更新图形,然后暂停1.0秒
#在取出电脑选择的球之前。这样,玩家就可以“看到”游戏了
#中间地位。也许可以考虑一种更好的方式来表达这一点。
updateGraphics()
睡眠(1.0)
计算机最大球数=最小值(3,球数保持)
#当然可以更改此代码,使计算机能够更智能地播放!
compBallsTaken=random.randint(1,computerMaxBalls)
self.numberOfBallsRemaining=self.numberOfBallsRemaining-compBallsTaken
###移除计算机选择的球后,再次更新图形。
updateGraphics()
打印(“计算机拿走了{}个球。{}个剩余。”.format(compBallsTaken,self.numberOfBallsRemaining))
如果self.numberOfBallsRemaining==0:
打印(“计算机获胜!”)
#用于放置球的全局变量
画布高度=200
画布宽度=610
画布边界缓冲区=10
maxBallSize=100
#下面的全局变量值是在initializeNimAndGUI中计算和设置的
#球形
#半球大小
#球间距
#最左球位置
#球位
# 1. 清理画布
# 2. 在画布上画出与Nim游戏中剩余数量相等的球
def updateGraphics():
canvas.delete('all'))
centerX=左MOSTBALLxposition
中心位置=球形位置
对于范围内的i(nimGame.remainingBalls()):
画布。创建椭圆(centerX-半圆球大小,
中心-半球大小,
centerX+半圆球尺寸,
centerY+半圆球尺寸,
fill=“#9999ff”)
centerX=centerX+球与球之间的间距+球大小
canvas.update_idletasks()
#GUI按钮调用的回调函数
def takeBalls(数字Take):
nimGame.take(数字take)
def initializeNewGame():
numberOfBalls=e1.get()#将此更改为从添加到GUI的条目小部件读取
初始化EnimandGUI(numberOfBalls)
#####
# 1. 创建具有指定球数的NimGame对象
# 2. 清除图形画布
# 3. 根据球的数量,计算球的大小和间距,并设置
#用于绘制球的全局变量。
# 
def初始化ENIMANDGUI(球数):
全球游戏
全局球大小、半球大小、球之间的空间、最左侧球位置、球位置
nimGame=nimGame(球数)
canvas.delete('all'))
ballSize=min(maxBallSize,int(((canvasWidth canvasBorderBuffer)//numberOfBalls)/1.2))
半球大小=球大小//2
spaceBetweenBalls=int(0.2*ballSize)
leftmostBallXPosition=(canvasBorderBuffer//2)+(球与球之间的空格//2)+半球大小
ballYPosition=画布高度//2
updateGraphics()
statusLabel.configure(text=“开始新游戏”)
#为Nim游戏创建GUI,包括
# 1. 将显示球的画布
# 2. 画布右侧的一些按钮,用于取球或开始新游戏
# 3. 画布和按钮下方的状态消息标签
#
def createGUI():
德国劳埃德船级社
    # Note: if you want to use additional tkinter widgets, you will need to add their names to
    # the import list below
    from tkinter import Tk, Canvas, Frame, Button, Label, Entry, END, LEFT, RIGHT, SUNKEN
    from time import sleep
    import random

    # To run this code, load into Python, and execute runNim(n), where n is desired initial number
    # of balls, in the Python shell
    #

    # This class is just like the solution to HW 6 Q2 with three small changes related to GUI.
    # See comments starting with # ##.
    class NimGame():

        def __init__(self, numberOfBalls):
            self.numberOfBallsRemaining = numberOfBalls
            print("Nim game initialized with {} balls.".format(self.numberOfBallsRemaining))

        def remainingBalls(self):
            return self.numberOfBallsRemaining

        def take(self, numberOfBalls):
            if (numberOfBalls < 1) or (numberOfBalls > 3) or (numberOfBalls > self.numberOfBallsRemaining):
                print("You can't take that number of balls. Try again.")
                # ## Update statusLabel in the GUI to tell user they can't take that many balls.
                # For the homework, you'll deactivate the buttons that allow such choices,
                # so this whole "if" will no longer be used/necessary.
                statusLabel.configure(text="You can't take that number of balls. Try again.")
            else:
                self.numberOfBallsRemaining = self.numberOfBallsRemaining - numberOfBalls
                print("You took {} balls. {} remain.".format(numberOfBalls, self.numberOfBallsRemaining))
                if self.numberOfBallsRemaining == 0:
                    print("You win!")
                else:
                    # ## After removing player-chosen balls, update graphics and then pause for 1.0 seconds
                    # before removing computer-chosen balls.  This way the player can "see" the
                    # intermediate status.  Perhaps think about a nicer way of showing this.
                    updateGraphics()
                    sleep(1.0)

                    computerMaxBalls = min(3, self.numberOfBallsRemaining)
                    # It is certainly okay to change this code so that the computer plays more intelligently!
                    compBallsTaken = random.randint(1,computerMaxBalls)
                    self.numberOfBallsRemaining = self.numberOfBallsRemaining - compBallsTaken

                    # ## After removing computer-chosen balls, update graphics again.
                    updateGraphics()
                    print("Computer took {} balls. {} remain.".format(compBallsTaken, self.numberOfBallsRemaining))
                    if self.numberOfBallsRemaining == 0:
                        print("Computer wins!")

    # global variables used for placement of balls
    canvasHeight = 200
    canvasWidth = 610
    canvasBorderBuffer = 10
    maxBallSize = 100
    # the values of global variables below are computed and set in initializeNimAndGUI
    # ballSize
    # halfBallSize 
    # spaceBetweenBalls 
    # leftmostBallXPosition
    # ballYPosition

    # 1. clear the canvas
    # 2. draw balls on canvas equal to number remaining in the Nim game
    def updateGraphics():
        canvas.delete('all')   
        centerX = leftmostBallXPosition
        centerY = ballYPosition
        for i in range(nimGame.remainingBalls()):
            canvas.create_oval(centerX - halfBallSize,
                               centerY - halfBallSize,
                               centerX + halfBallSize,
                               centerY + halfBallSize,
                               fill="#9999ff")
            centerX = centerX + spaceBetweenBalls + ballSize
            canvas.update_idletasks()


    # Callback functions invoked by GUI buttons

    def takeBalls(numberToTake):
        nimGame.take(numberToTake)

    def initializeNewGame():
        numberOfBalls = e1.get() # change this to read from Entry widget you add to GUI
        initializeNimAndGUI(numberOfBalls)   

    #####

    # 1. create a NimGame object with specified number of balls
    # 2. clear the graphics canvas
    # 3. based on number of balls, compute values ball size and spacing and set
    #     global variable used for drawing the balls.
    # 
    def initializeNimAndGUI(numberOfBalls):
        global nimGame
        global ballSize, halfBallSize, spaceBetweenBalls, leftmostBallXPosition, ballYPosition

        nimGame = NimGame(numberOfBalls)
        canvas.delete('all') 
        ballSize = min(maxBallSize, int(((canvasWidth-canvasBorderBuffer)//numberOfBalls)/1.2))
        halfBallSize = ballSize // 2
        spaceBetweenBalls = int(0.2 * ballSize)
        leftmostBallXPosition = (canvasBorderBuffer//2) + (spaceBetweenBalls//2) + halfBallSize
        ballYPosition = canvasHeight // 2

        updateGraphics()
        statusLabel.configure(text="Started new game.")


    # create GUI for Nim Game, including
    # 1. canvas where balls will be shown
    # 2. some buttons, to the right of the canvas, for taking balls or starting a new game
    # 3. a label, below the canvas and buttons, for status messages
    #
    def createGUI():
        global rootWindow
        global canvas
        global statusLabel
        global textEntry

        rootWindow = Tk()
        rootWindow.title("Play Nim")
        canvasAndButtons = Frame(rootWindow)
        canvas = Canvas(canvasAndButtons, height=canvasHeight, width=canvasWidth, relief=SUNKEN, borderwidth=2)
        canvas.pack(side=LEFT)

        buttonframe = Frame(canvasAndButtons)
        button1 = Button(buttonframe, text='Take 1', command=lambda:takeBalls(1))
        button2 = Button(buttonframe, text='Take 2', command=lambda:takeBalls(2))
        button3 = Button(buttonframe, text='Take 3', command=lambda:takeBalls(3))
        button4 = Button(buttonframe, text='New Game', command=initializeNewGame)

        # replace this with an Entry widget
        e1 = Entry(rootWindow, bd=1)

        button1.pack()
        button2.pack()
        button3.pack()
        button4.pack()
        e1.pack(side=RIGHT)
        buttonframe.pack(side=RIGHT)
        canvasAndButtons.pack()
        statusLabel = Label(rootWindow)
        statusLabel.pack()

    # Call 'runNim' with the desired number of initial balls
    #
    def runNim(numberOfBalls):
        createGUI()
        initializeNimAndGUI(numberOfBalls)   
        rootWindow.mainloop()