首页 > 解决方案 > 如何使用按钮布局解决此 Python tkinter 问题

问题描述

我在 python 中做了一个石头剪刀布游戏,一切都很好,直到我添加了图片。看看我的代码:

player_score=0
comp_score=0
def press():
    print("You Pressed ROCK")
    ent=1
    global player_score
    global comp_score
    for i in range(0,1):
        comp_ent=(random.randint(1,3))
    if comp_ent==3:
        print("You won...Computer Choose Scissors")
        player_score+=1
    elif comp_ent==2:
        print("You Lose...Computer Choose Paper")
        comp_score+=1
    else:
        print("It's a Draw...Computer Choose Rock")
    print("Player Score:",player_score)
    print("Computer Score:",comp_score)    
    print("\n")
def press1():
    print("You Pressed PAPER")
    ent=2
    global player_score
    global comp_score
    for i in range(0,1):
        comp_ent=(random.randint(1,3))
    if comp_ent==1:
        print("You won...Computer Choose Rock")
        player_score+=1
    elif comp_ent==3:
        print("You Lose...Computer Choose Scissors")
        comp_score+=1
    else:
        print("It's a Draw...Computer Choose Paper")
    print("Player Score:",player_score)
    print("Computer Score:",comp_score)
    print("\n")
def press2():
    print("You Pressed SCISSORS")
    ent=3
    global player_score
    global comp_score    
    for i in range(0,1):
        comp_ent=(random.randint(1,3))
    if comp_ent==2:
        print("You won...Computer Choose Paper")
        player_score+=1
    elif comp_ent==1:
        print("You Lose...Computer Choose Rock")
        comp_score+=1
    else:
        print("It's a Draw...Computer Choose Scissors")
    print("Player Score:",player_score)
    print("Computer Score:",comp_score)    
    print("\n")
import random
from tkinter import *
import tkinter as tk
root = tk.Tk()
photo1=PhotoImage(file=r"C:\Users\Abhinav\Desktop\Important Folder\Python Project\rock2.gif")
photo2=PhotoImage(file=r"C:\Users\Abhinav\Desktop\Important Folder\Python Project\paper2.gif")
photo3=PhotoImage(file=r"C:\Users\Abhinav\Desktop\Important Folder\Python Project\scissors 2.gif")
frame = tk.Frame(root)
frame.pack()
button = tk.Button(root)
button.config(image=photo1,width="300",height="200",text="ROCK",fg="Black",command=press)
button.pack(side=TOP)
button2 = tk.Button(root)
button.config(image=photo2,width="300",height="200",text="PAPER",fg="Blue",command=press1)
button2.pack(side=BOTTOM)
button3 = tk.Button(root)
button3.config(image=photo3,width="300",height="200",text="SCISSORS",fg="Green",command=press2)
button3.pack(side=LEFT)
button3.config(image=photo3)
root.mainloop()

我正在为我的学校项目做这个。

截屏

标签: pythonimagebuttontkinterlayout

解决方案


那是因为你拼错button2buttonin button.config(image=photo2,...)。应该是button2.config(image=photo2, ...)


推荐阅读