Eine Funktion von Zeit zu Zeit aufrufen

Fragen zu Tkinter.
Antworten
Dexter1997
User
Beiträge: 92
Registriert: Sonntag 2. Dezember 2012, 21:13

Ich habe ein Programm geschrieben, dass bei Klick auf einen Knopf Geld erzeugt.
Jetzt soll pro Sekunde die Variable money erhöht werden. Wie erreiche ich das?

Code: Alles auswählen

from tkinter import *

money = 0
label2_added = False

def el(event):
	global money, label2, label2_added
	money += 1
	label["text"] = money

	if money == 10 and label2_added == False:
		label2.pack()
		#label2_added == True
		print("label2 added")



root = Tk()

label = Label(root, text=str(money))
label.pack()
button = Button(root, text="klick me")
button.bind("<Button>", el)
button.pack()

label2 = Label(root, text="Wonderful")

root.mainloop()
Sirius3
User
Beiträge: 17738
Registriert: Sonntag 21. Oktober 2012, 17:20

@Dexter1997: nicht dass die Frage hier schon tausend mal beantwortet wurde, zuletzt hier: Aktuelle Werte in Label.
Benutzeravatar
wuf
User
Beiträge: 1529
Registriert: Sonntag 8. Juni 2003, 09:50

Hi Dexter1997

Hier eine leicht angepasste Variante:

Code: Alles auswählen

#!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
    # Tkinter for Python 2.xx
    import Tkinter as tk
except ImportError:
    # Tkinter for Python 3.xx
    import tkinter as tk


APP_TITLE = "Money Rising"
APP_XPOS = 100
APP_YPOS = 100
APP_WIDTH = 300
APP_HEIGHT = 150

INC_TIME = 1000
LABEL_FONT = ('Helevetica', 30, 'bold')
LABEL_FG_COLOR = 'green'


class Application(tk.Frame):

    def __init__(self, parent, **kwargs):
        self.parent = parent
        
        tk.Frame.__init__(self, parent, **kwargs)
        
        self.money = 0
        self.money_flag = False
        self.money_var = tk.StringVar()
        tk.Label(self, textvariable=self.money_var, font=LABEL_FONT,
            fg=LABEL_FG_COLOR).pack(expand=True, pady=4)
        self.money_var.set(self.money)
        
        tk.Button(self, text="Rise the Money!", command=self.start_money_rising
            ).pack()
        
    def start_money_rising(self):
        if not self.money_flag:
            self.money_flag = True
            self.rise_money()
        
    def rise_money(self):
        if self.money < 10:
            self.money += 1
            self.money_var.set(self.money)
        else:
            self.money_var.set("Wonderfull!")
            self.money_flag = False
            self.money = 0
            return
            
        self.after(INC_TIME, self.rise_money)

        
def main():
    app_win = tk.Tk()
    app_win.title(APP_TITLE)
    app_win.geometry("+{}+{}".format(APP_XPOS, APP_YPOS))
    app_win.geometry("{}x{}".format(APP_WIDTH, APP_HEIGHT))
    
    Application(app_win).pack(expand=True)
    
    app_win.mainloop()
 
 
if __name__ == '__main__':
    main()      
Gruss wuf :wink:
Take it easy Mates!
Antworten