저는 파이썬 클래스를 위해 tkinter를 사용하여 간단한 추측 게임을 만들고 있습니다. 플레이어가 프로그램 전에 최대 추측 수를 가질 수 있도록 루프를 만드는 방법이 있는지 궁금합니다. 플레이어에게 번호가 무엇인지 알려주고 번호를 변경하거나 프로그램에 응답을 보낸 후 프로그램을 종료합니다. Heres는 지금까지 내 코드 :tkinter는 최대 버튼 클릭 수를 설정합니다
# This program is a number guessing game using tkinter gui.
# Import all the necessary libraries.
import tkinter
import tkinter.messagebox
import random
# Set the variables.
number = random.randint(1,80)
attempts = 0
# Start coding the GUI
class numbergameGUI:
def __init__(self):
# Create the main window.
self.main_window = tkinter.Tk()
# Create four frames to group widgets.
self.top_frame = tkinter.Frame()
self.mid_frame1 = tkinter.Frame()
self.mid_frame2 = tkinter.Frame()
self.bottom_frame = tkinter.Frame()
# Create the widget for the top frame.
self.top_label = tkinter.Label(self.top_frame, \
text='The number guessing game!')
# Pack the widget for the top frame.
self.top_label.pack(side='left')
# Create the widgets for the upper middle frame
self.prompt_label = tkinter.Label(self.mid_frame1, \
text='Guess the number I\'m thinking of:')
self.guess_entry = tkinter.Entry(self.mid_frame1, \
width=10)
# Pack the widgets for the upper middle frame.
self.prompt_label.pack(side='left')
self.guess_entry.pack(side='left')
# Create the widget for the bottom middle frame.
self.descr_label = tkinter.Label(self.mid_frame2, \
text='Your Guess is:')
self.value = tkinter.StringVar()
# This tells user if guess was too high or low.
self.guess_label = tkinter.Label(self.mid_frame2, \
textvariable=self.value)
# Pack the middle frame's widgets.
self.descr_label.pack(side='left')
self.guess_label.pack(side='left')
# Create the button widgets for the bottom frame.
self.guess_button = tkinter.Button(self.bottom_frame, \
text='Guess', \
command=self.guess,)
self.quit_button = tkinter.Button(self.bottom_frame, \
text='Quit', \
command=self.main_window.destroy)
# Pack the buttons.
self.guess_button.pack(side='left')
self.quit_button.pack(side='left')
# Pack the frames
self.top_frame.pack()
self.mid_frame1.pack()
self.mid_frame2.pack()
self.bottom_frame.pack()
# Enter the tkinter main loop.
tkinter.mainloop()
# Define guess
def guess(self):
# Get the number they guessed.
guess1 = int(self.guess_entry.get())
# sattempts +=1
# Tell player too low if their guess was too low.
if guess1 < number:
self.value.set('too low')
# Tell player too high if their guess was too high.
elif guess1 > number:
self.value.set('too high')
# End the loop if the player attempts the correct number.
if guess1 == number:
tkinter.messagebox.showinfo('Result', 'Congratulations! You guessed right!')
start = numbergameGUI()
나는 프로그램은 Tkinter를 사용했다하지만 난 아직 작동시킬 수되지 전에 나는 것을했기 때문에 추측 기능의 내부 while 루프를 넣어했습니다.
내가 그 생각했지만 나는 카운터 + = 1을 넣어 것 곳에서 같은 뭔가? (버튼을 누를 때마다 증가하도록) 카운터라고하는 완전히 새로운 함수를 정의하고 버튼에 두 번째 명령을 추가합니다 (가능한 경우)? – Trey
@ 트라이 :'추측 '에 넣어 –