2015-07-29 3 views
-1

В настоящее время я работаю над сканирующей ножницкой Tkinter GUI. Я хочу, чтобы иметь возможность рассчитать и сохранить # побед пользователя, компьютера и # связей. Я смог настроить IntVar() textvariable, чтобы связать с меткой, и каждый раз, когда пользователь выигрывает, он подсчитывает счет. Но единственная проблема заключается в том, что она только подсчитывает, например (пользователь рисует «Rock» и компьютер рисует «Scissors» [Мы знаем, что пользователь выигрывает], но в следующий раз, когда пользователь рисует рок, а компьютер рисует ножницы, count возвращается к 0). Он только подсчитывает один раз и сбрасывается и не переходит к следующему целому числу (поэтому он идет от 0 до 1, а затем возвращается к 0, а не к 2). Может ли кто-нибудь помочь мне сделать успешную переменную счетчика, которая учитывает количество побед и связей.Tkinter Label() Счетчик Variable

Код:

#Written by : Pamal Mangat. 
#Written on : Monday, July 27th, 2015. 
#Rock Paper Scissors : Version 1.2 (Tkinter [GUI] addition) 

from tkinter import * 
from sys import * 
from PIL import Image, ImageTk 
import pygame as py 
import os 
from random import randrange 

py.init() 

#Function runs the actual game. 
def runGame(startWindow): 

    #Close [startWindow] before advancing: 
    startWindow.destroy() 
    startWindow.quit() 

    master = Tk() 
    master.title('Lets Play!') 

    #Function carries on the remainder of the game. 
    def carryGame(button_id): 

     #Initial Values 
     userWins = 0 
     ties = 0 
     computerWins = 0 

     label_one = Label(master, text='Player Wins: ', font='Helvetica 11 bold', bg='PeachPuff2') 
     label_one.place(x=15, y=210) 

     label_two = Label(master, text='Ties: ', font='Helvetica 11 bold', bg='PeachPuff2') 
     label_two.place(x=195, y=210) 

     label_three = Label(master, text='Computer Wins: ', font='Helvetica 11 bold', bg='PeachPuff2') 
     label_three.place(x=295, y=210) 

     userWin_Text = IntVar() 
     userWin_Text.set(userWins) 

     ties_Text = IntVar() 
     ties_Text.set(ties) 

     computerWin_Text = IntVar() 
     computerWin_Text.set(computerWins) 

     userWin_Label = Label(master, textvariable = userWin_Text, font='Helvetica 10 bold', bg='PeachPuff2') 
     userWin_Label.place(x=110, y=210) 

     ties_Label = Label(master, textvariable = ties_Text, font='Helvetica 10 bold', bg='PeachPuff2') 
     ties_Label.place(x=240, y=210) 

     computerWin_Label = Label(master, textvariable = computerWin_Text, font='Helvetica 10 bold', bg='PeachPuff2') 
     computerWin_Label.place(x=420, y=210) 

     result = StringVar() 
     printResult = Label(master, textvariable = result, font='Bizon 32 bold', bg='PeachPuff2') 
     printResult.place(x=130, y=300) 

     #Computer's move: 
     random_Num = randrange(1,4) 

     if random_Num == 1: 
      computer_Move = 'Rock  ' 
      result.set(computer_Move) 

     elif random_Num == 2: 
      computer_Move = 'Paper  ' 
      result.set(computer_Move) 

     else: 
      computer_Move = 'Scissors' 
      result.set(computer_Move) 

     if button_id == 1: 
      player_Move = 'Rock' 

     elif button_id == 2: 
      player_Move = 'Paper' 

     else: 
      player_Move = 'Scissors' 

     if player_Move == 'Rock' and computer_Move == 'Scissors': 
      userWins += 1 
      userWin_Text.set(userWins) 


    #Rock button 
    rock_Button = Button(master, width=15, height=7, command=lambda:carryGame(1)) 
    rock_photo=PhotoImage(file=r'C:\Users\Pamal\Desktop\Documents\Python Folder\Python Projects\Rock, Paper, Scissors\V 1.2\Images\rock.png') 
    rock_Button.config(image=rock_photo,width="120",height="120") 
    rock_Button.place(x=17, y=70) 

    #Paper button 
    paper_Button = Button(master, width=15, height=7, command=lambda:carryGame(2)) 
    paper_photo=PhotoImage(file=r'C:\Users\Pamal\Desktop\Documents\Python Folder\Python Projects\Rock, Paper, Scissors\V 1.2\Images\paper.png') 
    paper_Button.config(image=paper_photo,width="120",height="120") 
    paper_Button.place(x=167, y=70) 

    #Scissors button 
    scissors_Button = Button(master, width=15, height=7, command=lambda:carryGame(3)) 
    scissors_photo=PhotoImage(file=r'C:\Users\Pamal\Desktop\Documents\Python Folder\Python Projects\Rock, Paper, Scissors\V 1.2\Images\scissors.png') 
    scissors_Button.config(image=scissors_photo,width="120",height="120") 
    scissors_Button.place(x=317, y=70) 

    label_1 = Label(master, text='Please make your selection-', font='Bizon 20 bold', bg='PeachPuff2') 
    label_1.pack(side=TOP) 

    label_2 = Label(master, text='The computer picked:', font='Helvetica 22 bold', bg='PeachPuff2') 
    label_2.place(x=70, y=240) 

    #Locks window size 
    master.maxsize(450, 400) 
    master.minsize(450, 400) 

    #Sets window background to PeachPuff2 
    master.config(background='PeachPuff2') 

    master.mainloop() 

def startScreen(): 

    #Plays music for the application 
    def playMusic(fileName): 
     py.mixer.music.load(fileName) 
     py.mixer.music.play() 

    #Start Window 
    startWindow = Tk() 
    startWindow.title('[Rock] [Paper] [Scissors]') 

    #Imports image as title 
    load = Image.open(r'C:\Users\Pamal\Desktop\Documents\Python Folder\Python Projects\Rock, Paper, Scissors\V 1.2\Images\title.png') 
    render = ImageTk.PhotoImage(load) 
    img = Label(startWindow, image=render, bd=0) 
    img.image = render 
    img.place(x=-100, y=-65) 

    clickToPlay = Button(startWindow, text='Play!', width=8, font='Bizon 20 bold', bg='Black', fg='Yellow', relief=RIDGE, bd=0, command=lambda:runGame(startWindow)) 
    clickToPlay.place(x=75, y=125) 

    #Credit 
    authorName = Label(startWindow, text='Written by : Pamal Mangat', font='Times 6 bold', bg='Black', fg='Yellow') 
    authorName.place(x=2, y=230) 

    versionNum = Label(startWindow, text='[V 1.2]', font='Times 6 bold', bg='Black', fg='Red') 
    versionNum.place(x=268, y=230) 

    #Start Screen Music 
    playMusic(r'C:\Users\Pamal\Desktop\Documents\Python Folder\Python Projects\Rock, Paper, Scissors\V 1.2\Audio\title_Song.mp3') 

    #Locks window size 
    startWindow.maxsize(300, 250) 
    startWindow.minsize(300, 250) 

    #Sets window background to black 
    startWindow.config(background='Black') 

    startWindow.mainloop() 

startScreen() 

ScreenShots:

Изображение произведенного окна: enter image description here

+0

Просьба указать [mcve]; большинство из того, что вы предоставили, не имеет отношения к вашей проблеме. – jonrsharpe

ответ

1

Вы повторно инициализировать Встречное переменные каждый время carryGame запускается. Извлечение их на более высокий уровень охвата, так что они только инициализируется один раз:

РЕДАКТИРОВАТЬ: Тест

from tkinter import * 
from sys import * 
from PIL import Image, ImageTk 
import pygame as py 
import os 
from random import randrange 



#Initial Values 
userWins = 0 
ties = 0 
computerWins = 0 
py.init() 


#Function runs the actual game. 
def runGame(startWindow): 

    #Close [startWindow] before advancing: 
    startWindow.destroy() 
    startWindow.quit() 

    master = Tk() 
    master.title('Lets Play!') 

    #Function carries on the remainder of the game. 
    def carryGame(button_id): 

     #Initial Values 
     global userWins 
     global ties 
     global computerWins 

     label_one = Label(master, text='Player Wins: ', font='Helvetica 11 bold', bg='PeachPuff2') 
     label_one.place(x=15, y=210) 

     label_two = Label(master, text='Ties: ', font='Helvetica 11 bold', bg='PeachPuff2') 
     label_two.place(x=195, y=210) 

     label_three = Label(master, text='Computer Wins: ', font='Helvetica 11 bold', bg='PeachPuff2') 
     label_three.place(x=295, y=210) 

     userWin_Text = IntVar() 
     userWin_Text.set(userWins) 

     ties_Text = IntVar() 
     ties_Text.set(ties) 

     computerWin_Text = IntVar() 
     computerWin_Text.set(computerWins) 

     userWin_Label = Label(master, textvariable = userWin_Text, font='Helvetica 10 bold', bg='PeachPuff2') 
     userWin_Label.place(x=110, y=210) 

     ties_Label = Label(master, textvariable = ties_Text, font='Helvetica 10 bold', bg='PeachPuff2') 
     ties_Label.place(x=240, y=210) 

     computerWin_Label = Label(master, textvariable = computerWin_Text, font='Helvetica 10 bold', bg='PeachPuff2') 
     computerWin_Label.place(x=420, y=210) 

     result = StringVar() 
     printResult = Label(master, textvariable = result, font='Bizon 32 bold', bg='PeachPuff2') 
     printResult.place(x=130, y=300) 

     #Computer's move: 
     random_Num = randrange(1,4) 

     if random_Num == 1: 
      computer_Move = 'Rock  ' 
      result.set(computer_Move) 

     elif random_Num == 2: 
      computer_Move = 'Paper  ' 
      result.set(computer_Move) 

     else: 
      computer_Move = 'Scissors' 
      result.set(computer_Move) 

     if button_id == 1: 
      player_Move = 'Rock' 

     elif button_id == 2: 
      player_Move = 'Paper' 

     else: 
      player_Move = 'Scissors' 

     if player_Move == 'Rock' and computer_Move == 'Scissors': 
      userWins += 1 
      userWin_Text.set(userWins) 


    #Rock button 
    rock_Button = Button(master, width=15, height=7, command=lambda:carryGame(1)) 
    rock_photo=PhotoImage(file=r'C:\Users\Pamal\Desktop\Documents\Python Folder\Python Projects\Rock, Paper, Scissors\V 1.2\Images\rock.png') 
    rock_Button.config(image=rock_photo,width="120",height="120") 
    rock_Button.place(x=17, y=70) 

    #Paper button 
    paper_Button = Button(master, width=15, height=7, command=lambda:carryGame(2)) 
    paper_photo=PhotoImage(file=r'C:\Users\Pamal\Desktop\Documents\Python Folder\Python Projects\Rock, Paper, Scissors\V 1.2\Images\paper.png') 
    paper_Button.config(image=paper_photo,width="120",height="120") 
    paper_Button.place(x=167, y=70) 

    #Scissors button 
    scissors_Button = Button(master, width=15, height=7, command=lambda:carryGame(3)) 
    scissors_photo=PhotoImage(file=r'C:\Users\Pamal\Desktop\Documents\Python Folder\Python Projects\Rock, Paper, Scissors\V 1.2\Images\scissors.png') 
    scissors_Button.config(image=scissors_photo,width="120",height="120") 
    scissors_Button.place(x=317, y=70) 

    label_1 = Label(master, text='Please make your selection-', font='Bizon 20 bold', bg='PeachPuff2') 
    label_1.pack(side=TOP) 

    label_2 = Label(master, text='The computer picked:', font='Helvetica 22 bold', bg='PeachPuff2') 
    label_2.place(x=70, y=240) 

    #Locks window size 
    master.maxsize(450, 400) 
    master.minsize(450, 400) 

    #Sets window background to PeachPuff2 
    master.config(background='PeachPuff2') 

    master.mainloop() 

def startScreen(): 

    #Plays music for the application 
    def playMusic(fileName): 
     py.mixer.music.load(fileName) 
     py.mixer.music.play() 

    #Start Window 
    startWindow = Tk() 
    startWindow.title('[Rock] [Paper] [Scissors]') 

    #Imports image as title 
    load = Image.open(r'C:\Users\Pamal\Desktop\Documents\Python Folder\Python Projects\Rock, Paper, Scissors\V 1.2\Images\title.png') 
    render = ImageTk.PhotoImage(load) 
    img = Label(startWindow, image=render, bd=0) 
    img.image = render 
    img.place(x=-100, y=-65) 

    clickToPlay = Button(startWindow, text='Play!', width=8, font='Bizon 20 bold', bg='Black', fg='Yellow', relief=RIDGE, bd=0, command=lambda:runGame(startWindow)) 
    clickToPlay.place(x=75, y=125) 

    #Credit 
    authorName = Label(startWindow, text='Written by : Pamal Mangat', font='Times 6 bold', bg='Black', fg='Yellow') 
    authorName.place(x=2, y=230) 

    versionNum = Label(startWindow, text='[V 1.2]', font='Times 6 bold', bg='Black', fg='Red') 
    versionNum.place(x=268, y=230) 

    #Start Screen Music 
    playMusic(r'C:\Users\Pamal\Desktop\Documents\Python Folder\Python Projects\Rock, Paper, Scissors\V 1.2\Audio\title_Song.mp3') 

    #Locks window size 
    startWindow.maxsize(300, 250) 
    startWindow.minsize(300, 250) 

    #Sets window background to black 
    startWindow.config(background='Black') 

    startWindow.mainloop() 

startScreen() 

Вот изображение кода выполняется: (Это делает подсчет правильно) enter image description here

Но как только другая команда выполняется (разн. кнопка нажата) отсчет идет к тому, 0. enter image description here

Но если пользователь снова побеждает, то появляется счетчик. enter image description here

ТАК КАК Я ХРАНИТЕ НОМЕР НА ЭКРАНЕ ВСЕ ВРЕМЯ?

+0

Является ли глобальное атрибутное ключевое слово глобальными переменными (что он делает)? И да, я знаю, это может показаться глупым вопросом. –

+0

А также как я могу их подсчитывать каждый раз, когда пользователь выигрывает? –

+0

А также что такое более высокий уровень охвата? –