简体   繁体   中英

root = tkinter.Tk() or root = Tk()?

I have two scripts that both work:

import tkinter
root = tkinter.Tk()
root.configure(bg='blue')
root.mainloop()

and

from tkinter import *
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello world!")
text.pack()
root.mainloop()

I want to combine the two scripts to print the text on a blue background, but moving anything from one script to another seems to break it.

I can't figure out if it's about root = tkinter.Tk() vs root = Tk() , or import tkinter vs from tkinter import * , or something entirely different. I can't find a successful combination.

I'm using Ubuntu and Python 3.6.9.

Because you use two different styles when importing tkinter, you will need to modify the code from one file when moving to the other. The code in your first example is the preferred way to do it because PEP8 discourages wildcard imports.

When when you copy the code from the second example, you'll need to add tkinter. to every tkinter command ( tkinter.Tk() , tkinter.Text(root) , tk.INSERT , etc.

Personally I find import tkinter as tk to be a slight improvement. I find tk.Tk() to be a little easier to type and read than tkinter.Tk() .

You should know that:

from tkinter import *

will import all the attribute in the tkinter .But if you also define some variable in your script.It will be covered by your new variable.So we don't recommend you to use that.(If you used both from tkinter.ttk import * and from tkinter import * .Some default widgets of tkinter will be covered by ttk widgets.)

Just like Mr.Bryan said,I'd like to use import tkinter as tk ,too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM