Tkinter help - Why this behavior ? (py3)

rantingrick rantingrick at gmail.com
Wed Jun 9 12:49:08 EDT 2010


On Jun 5, 8:46 am, Dodo <dodo_do_not_wake... at yahoo.Fr> wrote:
> Hi,
>
> let's consider this exemple :
>
> from tkinter import *
> from tkinter.ttk import *
>
> class First:
>         def __init__(self):
>                 self.root = Tk()
>                 B = Button(self.root, command=self.op)
>                 B.pack()
>
>                 self.root.mainloop()
>
>         def op(self):
>                 Second(self)
>                 print("print")
>
> class Second:
>         def __init__(self, parent):
>                 root = Toplevel(parent.root)
>                 root.grab_set()
>
>                 root.mainloop()
>


Please don't write code like this, it is very, very, very, very ugly.
Python is an OOP language do use that to your advantage and you will
make your life much easier! Here is a better alternative.


import Tkinter as tk
from Tkconstants import *
import tkSimpleDialog

class MyDialog(tkSimpleDialog.Dialog):
    def body(self, master):
        prompt = "Hello from my custom dialog!\nAlthough with
something this simple i should have used tkMessageBox."
        tk.Label(self, text=prompt).pack()

    def validate(self):
        print 'I need to put some code here, maybe'
        return True

    def apply(self):
        print 'I need to put some code here, maybe'


class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        b=tk.Button(self, text='Show Dialog', command=self.showDialog)
        b.pack(padx=5, pady=5)

    def showDialog(self):
        d = MyDialog(self)

if __name__ == '__main__':
    app = App()
    app.mainloop()



More information about the Python-list mailing list