简体   繁体   中英

using a function to create a button in a second window in tkinter

Hello I am working on a screenshot related python project using tkinter. In my program I have a second window opened by a button press code below.

#Opens the second window
def open_win2():
    global sec_window
    sec_window = Toplevel()
    sec_window.config(height = 1800,width = 1800, bg = "chocolate1")
    sec_picture_box = Label(sec_window,height=800, width=800, image=mainview)
    sec_picture_box.place(x=800, y=100)

I want to create a function that when called will create a button in the second window. Is this remotely possible. I have tried to do the most simple thing I could think of to test if it can be done (Open a lable when called) the code for the function is which is the command of a button on the root window

def create_secondwindow_button():
    screenshot_snap = Label(text = "dog",)
    screenshot_snap.grid(sec_window,column = 1, row = 1)

I just get the error message

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Link\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/Users/Link/PycharmProjects/Helloworld/main.py", line 67, in create_secondwindow_button
    screenshot_snap.grid(sec_window,column = 1, row = 1)
  File "C:\Users\Link\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2226, in grid_configure
    + self._options(cnf, kw))
_tkinter.TclError: bad option "-bd": must be -column, -columnspan, -in, -ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky

Process finished with exit code 0

If you cant do this do you have to imbed your function within the function that opens the second window? Thanks a bunch for any help!

This is how the function should be:

def create_secondwindow_button():
    screenshot_snap = Label(sec_window, text="dog")
    screenshot_snap.grid(column=1, row=1)

Also there is no space between kwarg arguments as You can see in my code (per PEP 8 at least).

Also also if You wanted to create a button, it should be:

def create_secondwindow_button():
    screenshot_snap = Button(sec_window, text="dog")
    screenshot_snap.grid(column=1, row=1)

And just in case You do, don't do this:

from tkinter import *

It is bad practice in general and You should either import what you need:

from tkinter import Tk, Label, Button

Or import the module like this

import tkinter

or

import tkinter as tk

(for example You can use as as You need for example You might as well say as kinter or sth)

In such case You would need to refer like this:

tk.Button
tk.Label

And so on...

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