우선 여기에 프로그램의 배경이 있습니다.Python Tkinter에서 윈도우 업데이트
나는 OOP와 GUI 개발을 통해 자신의 길을 찾고있다. 아래의 코드는 훌륭하지 않지만 GUI 및 OOP에서의 첫 번째 시도라는 것을 알고 있습니다.
내가 원하는 것을하고있다. (모두 매우 비효율적 일 수있다.)하지만 나는 플레이어에게 제공하는 정보에 문제가있다.
플레이어가 게임을 진행하면서 프로그램에서 수행해야 할 작업에 대해 묻습니다. 필자는 레이블과 기능 및 텍스트 위젯이없는 버튼으로이 작업을 시도했습니다 (이것은 완전한 실패였습니다).
영토를 객체로 생성 한 다음이를 사용하여 GUI 보드에 불을 붙일 수있는 프로그램을 얻을 수 있습니다. 그런 다음 사용자가 시작 영토를 선택하고 군대를 추가하도록 허용 할 수 있습니다. 나는 사용자가 공격 할 곳과 공격 할 곳을 선택할 수있는 섹션을 만드는 과정에 있습니다. 이 모든 것이 작동하고 있습니다 (패션으로).
그러나 내 질문은 ... 단추를 통해 기능을 통해 업데이트 할 때 여전히 이전 값을 표시합니다. 이 방법을 멈추고 최신 메시지를 표시하거나 매번 새로운 단추를 만드는 방법이 있습니까?
from tkinter import *
import random
class territory:
def __init__ (self, country, player = 0, current_armies = 0, x=0, y=0, pos=0, neighbours=""):
self.country = country
self.current_armies = current_armies
self.player = player
self.y = y
self.x = x
self.pos = pos
self.neighbours = neighbours
def get_armies(self):
print(self.country + " has " + str(self.current_armies)+ " armies.")
def add_armies (self, armies):
self.current_armies += armies
def roll_dice (self, dice=1):
rolls = []
for i in range(0, dice):
rolls.append(random.randint(1,6))
rolls.sort()
rolls.reverse()
print (self.country + " has rolled " + str(rolls))
return rolls
def owner(self):
print (self.country + " is owned by " + self.player)
def get_country(self):
print(country)
def create_territories():
countries = ["UK", "FRA", "SPA", "GER"]
terr_pos = [[0,1],[1,1],[1,2],[2,0]]
sta_arm = [1,1,1,1]
pos = [0,1,2,3]
neighb = [["FRA","SPA"],["UK","SPA","GER"],["FRA"],["FRA"]]
terr = []
for i in range(len(countries)):
terr.append(territory(countries[i],0, sta_arm [i] ,
terr_pos[i][0],terr_pos[i][1], pos[i], neighb[i]))
return terr
## Button Commands
def claim_t(territory, i):
global player1_reserves, player2_reserves, cur_player, claimed, title
if territory[i].player == 0:
territory[i].player = cur_player
claimed += 1
if cur_player == 1:
cur_player = 2
else:
cur_player = 1
else:
print("Teritory already claimed. Choose again")
if claimed == len(territory):
title = "Add Armies"
message = ("player " + str(cur_player) + " add army to one of your territories.")
army_board (territory)
else:
claim_board(territory)
def add_army (territories, i):
global player1_reserves, player2_reserves, cur_player, title
if territories[i].player == cur_player:
if cur_player == 1:
if player1_reserves >0:
territories[i].current_armies += 1
player1_reserves -= 1
print(player1_reserves)
cur_player = 2
else:
print("You have no reserves left")
cur_player = 2
else:
if player2_reserves >0:
territories[i].current_armies += 1
player2_reserves -= 1
print(player2_reserves)
cur_player = 1
else:
print("You have no reserves left")
cur_player = 1
army_board (territories)
else:
print("Not your territory")
if player1_reserves == 0 and player2_reserves == 0:
cur_player = 1
play_board(territories)
else:
print ("Player " + str(cur_player) +
" add army to one of your territories.")
def run_game (territories, i):
global attacker, defender, cur_player, attack_defend, message
if attack_defend == "attack":
attacker = i
message = str(cur_player) + " has chosen to attack from " +territories[i].country + ". Choose target country."
attack_defend = "defend"
play_board (territories)
else:
if territories[i].country in territories[attacker].neighbours:
message = "Valid Attack"
defender = i
attack_defend = "attack"
play_board(territories)
else:
message = "You can't attack " + territories[i].country + " from " + territories[attacker].country + " Choose again"
play_board(territories)
## Board Builders
def claim_board(territories):
global cur_player
buttonUk = Button(text = territories[0].country + " p= " +
str(territories[0].player), width = 10,
command=lambda: claim_t(territories, 0),
fg = "red").grid(row=territories[0].y,column=territories[0].x)
buttonFRA = Button(text = territories[1].country + " p= " +
str(territories[1].player), width = 10,
command=lambda: claim_t(territories, 1)).grid(row=territories[1].y,column=territories[1].x)
buttonSpa = Button(text = territories[2].country + " p= " +
str(territories[2].player),
width = 10, command=lambda: claim_t(territories, 2)).grid(row=territories[2].y,column=territories[2].x)
buttonGER = Button(text = territories[3].country + " p= " +
str(territories[3].player), width = 10,
command=lambda: claim_t(territories, 3)).grid(row=territories[3].y,column=territories[3].x)
label = Label (text = "Claim your territories").grid(row=4, column = 1)
label_1 = Label (text = "player " + str(cur_player) +
" add army to one of your territories.").grid(row=4, column = 1)
def army_board (territories):
global cur_player, player1_reserves, player2_reserves
buttonUk = Button(text = territories[0].country+
" a= "+str(territories[0].current_armies) +
" p= "+str(territories[0].player), width = 16,
command=lambda: add_army(territories, 0)).grid(row=territories[0].y,column=territories[0].x)
buttonFRA = Button(text = territories[1].country+
" a= "+str(territories[1].current_armies)+
" p= "+str(territories[1].player), width = 16,
command=lambda: add_army(territories, 1)).grid(row=territories[1].y,column=territories[1].x)
buttonSpa = Button(text = territories[2].country+
" a= "+str(territories[2].current_armies)+
" p= "+str(territories[2].player), width = 16,
command=lambda: add_army(territories, 2)).grid(row=territories[2].y,column=territories[2].x)
buttonGER = Button(text = territories[3].country+
" a= "+str(territories[3].current_armies)+
" p= "+str(territories[3].player), width = 16,
command=lambda: add_army(territories, 3)).grid(row=territories[3].y,column=territories[3].x)
label = Label (text = "Place your armies").grid(row=4, column = 1, columnspan = 4)
label = Label (text = "Player " + str(cur_player) +
" place a reserve ").grid(row=5, column = 1, columnspan = 5)
if cur_player == 1:
reserves = player1_reserves
else:
reserves = player2_reserves
label = Button (text = "Player " + str(cur_player) +
" you have " + str(reserves) +
" reserves to place").grid(row=5, column = 1, columnspan = 4)
print("Player " + str(cur_player) +
" you have " + str(reserves) +
" reserves to place")
def play_board (territories):
global cur_player, attacker, defender, message
buttonUk = Button(text = territories[0].country+
" a= "+str(territories[0].current_armies) +
" p= "+str(territories[0].player),
width = 16, command=lambda: run_game(territories, 0)).grid(row=territories[0].y,column=territories[0].x)
buttonFRA = Button(text = territories[1].country+
" a= "+str(territories[1].current_armies)+
" p= "+str(territories[1].player), width = 16, command=lambda: run_game(territories, 1)).grid(row=territories[1].y,column=territories[1].x)
buttonSpa = Button(text = territories[2].country+
" a= "+str(territories[2].current_armies)+
" p= "+str(territories[2].player), width = 16, command=lambda: run_game(territories, 2)).grid(row=territories[2].y,column=territories[2].x)
buttonGER = Button(text = territories[3].country+
" a= "+str(territories[3].current_armies)+
" p= "+str(territories[3].player), width = 16, command=lambda: run_game(territories, 3)).grid(row=territories[3].y,column=territories[3].x)
label = Label (text = "Now it is time to wage war").grid(row=4, column = 1)
label = Button (text = message).grid(row=5, column = 1)
print(message)
##Game Sections
def claim_territory (territory):
global claimed, title
window = Tk()
window.title ("Domination")
if claimed != len(territory):
claim_board(territory)
else:
window.destroy()
window.mainloop()
## Global Variables
territories = create_territories()
cur_player = 1
player1_reserves = 1
player2_reserves = 1
claimed = 0
attacker = ""
defender = ""
message = "Player " + str(cur_player) + " Select a location to attack from"
attack_defend = "attack"
## Running of Game
claim_territory(territories)
귀하의 버튼 저장하는 변수를 생성하는 기능에 로컬 : 여기 문서에서보세요. 기능이 끝나면 버튼이 작동하지 않게됩니다. – Marvo
나는 당신이 여기서 말하는 것을 이해한다고 생각합니다. 기본적으로 버튼은 이전 호출을 덮어 쓰지 않고 각 호출에서 다시 작성됩니다. 나는 창을 지우고 창을 파괴하려했지만 어떤 이유로 창을 닫을 때 오류가 발생합니다. 나는 이것을 다시 방문하여 매번 보드 편집을 허용 할 클래스로 각 보드를 빌드하려고 노력할 것이다. 내 웹 검색에서 부족한 점이 있으면 조언을 얻을 수있는 위치에 대한 의견이나 조언을 보내 주시면 감사하겠습니다. –
[최소 완벽하고 검증 가능한 예제를 만드는 방법] (http://www.stackoverflow.com/help/mcve)을 읽어보십시오. –