Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

python - Why can I not instatiate a new Frame object in Tkinter?

I am trying to make an interactive graph that is displayed in the Tkinter window. However, I am not able to create a Frame object to place in the Grid of the Tkinter window.

I have created my Tkinter object in a class style here is the instantiation of it

window = Tk()
w = Graph(window, size, startX, startY, endX, endY)
window.geometry('1000x1000')
window.title('Tkinter Testing')
window.mainloop()

I am referring to this tutorial: Tkinter Geometry Manager

for x in range(len(self.graph)):
    for y in range(len(self.graph[0])):
        frame = window.Frame(
            master=window,
            relief=window.RAISED,
            borderwidth=1
        )
        frame.grid(row=x,column=y)
        label = window.Label(master = frame, text="testing")

This is the error thrown in the console

DEPRECATION WARNING: The system version of Tk is deprecated and may be removed in a future release. Please don't rely on it. Set TK_SILENCE_DEPRECATION=1 to suppress this warning.
Traceback (most recent call last):
  File "Graph.py", line 158, in <module>
    w = Graph(window, size, startX, startY, endX, endY)
  File "Graph.py", line 23, in __init__
    self.displayGraph()
  File "Graph.py", line 39, in displayGraph
    frame = window.Frame(
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1909, in __getattr__
    return getattr(self.tk, attr)
AttributeError: Frame

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Credit goes to @quamarana and @jasonharper for shedding light and explaining the issue.

The answer to this question had to do with how Tkinter is imported. The syntax when instantiating an object is slightly different based on the import statement.

import tkinter as tk or from tkinter import Tk

button = tk.Button(...
frame = tk.Frame(...
label = tk.Label(...

from tkinter import *

button = Button(...
frame = Frame(...
label = Label(...

As @jasonharper pointed out:

If you did from tkinter import *, you would instead have to say Tk() or Label() (this option is generally not recommended, since it's no longer obvious where the definitions of these names are coming from).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...