#python #class #tkinter #button
#python #класс #tkinter #кнопка
Вопрос:
В ShowMoneyButton
классе я хочу activation
, чтобы функция активировалась только в том случае, если значение self.button_activated
равно False , и я устанавливаю его как False при SongButton
запуске функции класса activation
, но он не регистрируется. Оно остается верным. Есть ли способ сделать так ShowMoneyButton
, чтобы функция активации класса выполнялась только при SongButton
activation
выполнении функции класса, за исключением первого раза?
import tkinter as tk, random, subprocess, time, os, datetime, pprint
class Song:
def __init__(self):
self.files = []
self.path = "/users/eliasrahoui/desktop/songy"
for filename in os.listdir(self.path):
self.files.append(self.path "/" filename)
class Money_Value:
def __init__(self):
with open("money_counter.txt", "r") as f:
a = f.read()
a = int(a)
self.current_value = a
class Clock:
def __init__(self, root):
money = Money_Value()
self.money = money.current_value
self.root = root
self.label = tk.Label(self.root, text = "$" str(self.money), foreground = "green", font = ('calibri', 100, 'bold'))
self.label.pack()
def countup(self, *args):
root = self.root
money_per_hour = 1000
self.money = 1
self.label['text'] = "$" str(self.money)
self.root_id = root.after(money_per_hour, self.countup)
def stop(self):
root = self.root
root.after_cancel(self.root_id)
with open("money_counter.txt", "w") as f:
f.write(str(self.money))
def save(self):
with open("money_counter.txt", "w") as f:
f.write(str(self.money))
self.root.destroy()
class Button:
all_buttons = {}
windows = []
return_code = []
button_activated = False
def __init__(self, root, text, command):
self.text = text
button = tk.Button(root, text = text, command = command)
self.all_buttons[self.text] = button
def remove(self, button):
button.pack_forget()
def show_button(self, button):
button.pack(side ="bottom")
class SongButton(Button):
def __init__(self, root, clock):
self.root = root
self.root_clock = clock
super().__init__(self.root, text = "stop song", command = self.activation)
def activation(self):
windows = self.windows
for i in windows:
i.destroy()
code = self.return_code[-1]
code.kill()
self.remove(self.all_buttons["stop song"])
self.root_clock.countup()
self.button_activated = False
class ShowMoneyButton(Button):
def __init__(self, root, clock):
self.root = root
super().__init__(self.root, "show me the money", self.activation)
song = Song()
self.songs = song.files
money_show_button = self.all_buttons["show me the money"]
self.show_button(money_show_button)
self.pic = tk.PhotoImage(file = "/users/eliasrahoui/desktop/IMG_7465.png")
#self.button_activated = False
self.label = tk.Label(self.root, text = "")
self.root_clock = clock
def activation(self):
if self.button_activated == False:
self.root_clock.stop()
num = Money_Value()
money = num.current_value
self.label.config(text =f'Money {money}')
self.label.pack()
random_song = random.choice(self.songs)
a = SongButton(self.root, self.root_clock)
return_cod = subprocess.Popen(["afplay", random_song])
self.return_code.append(return_cod)
self.show_button(self.all_buttons["stop song"])
self.button_activated = True
for _ in range(30):
root = self.root
window = tk.Toplevel(self.root)
self.windows.append(window)
window.minsize(100, 100)
window_label = tk.Label(window, image = self.pic)
window_label.pack()
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen
x = random.randint(0, ws)
y = random.randint(0, hs)
w = 200
h = 200
window.geometry('%dx%d %d %d' % (w, h, x, y))
class Timer(Button):
def __init__(self, root, start_time, name, counter = False):
self.count_down_start_time = start_time
self.root = root
self.name = name
self.counter = counter
self.tmp_counter = counter
super().__init__(self.root, text = name, command = self.timer_window)
self.show_button(self.all_buttons[self.name])
self.timer_id = None
self.window_label = None
self.orignial = start_time
self.window = None
self.current_question = 1
self.questions_answered = {}
self.times = [self.orignial]
self.positive = False
self.min_max = {}
def timer_window(self):
self.window = tk.Toplevel(self.root)
self.window.geometry('%dx%d %d %d' % (300, 200, 500, 300))
self.window_label = tk.Label(self.window, text = "", font = ('calibri', 100, 'bold'))
self.counter_label = tk.Label(self.window, text = f'Current Question: {self.current_question}')
self.window_label.pack()
self.timer()
def timer(self):
mins, secs = divmod(self.count_down_start_time, 60)
mins = abs(mins)
secs = abs(secs)
timerr = '{:02d}:{:02d}'.format(mins, secs)
if self.count_down_start_time == -1:
self.positive = True
self.window_label["foreground"] = "red"
if self.positive:
self.count_down_start_time = 1
else:
self.count_down_start_time -= 1
self.window_label["text"] = timerr
self.window.protocol("WM_DELETE_WINDOW", self.callback)
if self.counter == True:
button = tk.Button(self.window, text = "Question Done!", command = self.counter_func)
button.pack(side = "bottom")
button_report = tk.Button(self.window, text = "Report", command = self.report)
self.counter = False
self.counter_label.pack()
button_report.pack(side = "bottom")
self.timer_id = self.window.after(1000, self.timer)
def callback(self):
self.window.after_cancel(self.timer_id)
self.window.destroy()
self.count_down_start_time = self.orignial
if self.tmp_counter == True:
self.counter = True
self.current_question = 1
self.questions_answered = {}
self.positive = False
self.times = [self.orignial]
def counter_func(self):
self.questions_answered[self.current_question] = str(datetime.timedelta(seconds = self.times[-1] - self.count_down_start_time))
self.times.append(self.count_down_start_time)
self.current_question = 1
self.counter_label["text"] = f'Current Question: {self.current_question}'
def report(self):
vals = self.times_min_max()
new_window = tk.Toplevel(self.window)
new_window.minsize(300,300)
a = self.questions_answered[1]
data_pretty = pprint.pformat(self.questions_answered)
label = tk.Label(new_window, text = data_pretty)
label.pack()
mx = {f'Maximum time took per question: {vals[0]} question numbers': vals[2]}
mn = {f'Minimum time took per question: {vals[1]} question numbers': vals[-1]}
mx_label = tk.Label(new_window, text = mx, font = ('calibri', 14, 'bold'))
mn_label = tk.Label(new_window, text = mn, font = ('calibri', 14, 'bold'))
mn_label.pack(side = "bottom")
mx_label.pack(side = "bottom")
def times_min_max(self):
f = {}
big = []
small = []
for i in range(1, len(self.questions_answered) 1):
val = self.questions_answered[i]
if ":" in val:
q = val.split(":")
secs = int(q[-1])
mins = q[0]
secs = secs/60
secs = str(secs)
secs = secs.split(".")
secs = secs[-1]
final = mins "." secs
final = (float(final)) * 60
final = round(final)
f[i] = final
else:
f[i] = int(val)
max_val = max(f, key = f.get) #max(f.items(), key=operator.itemgetter(1))[0]
min_val = min(f, key=f.get)#min(f.keys(), key=(lambda key: f[key]))#min(f.items(), key = operator.intemgetter(1))[0]
min_val = f[min_val]
max_val = f[max_val]
for i in f.keys():
if f[i] == max_val:
big.append(i)
if f[i] == min_val:
small.append(i)
return (self.questions_answered[big[0]], self.questions_answered[small[0]], big, small)
основная функция:
import clocky_classy as cm
import tkinter as tk
root = tk.Tk()
root.minsize(400,200)
my_clock = cm.Clock(root)
money_button = cm.ShowMoneyButton(root, my_clock)
root.protocol("WM_DELETE_WINDOW", my_clock.save)
timer = cm.Timer(root, 120, "2 min timer")
timer = cm.Timer(root, 1800, "30 min timer", counter = True)
my_clock.countup()
root.mainloop()
Комментарии:
1. Где находится основная функция?
2. @JacksonPro Я добавил его rn
3. Что внутри вашего
money.txt
файла?4. целое число, например 200
5. @JacksonPro ^, а папка songy — это куча загрузок mp3