I created a tkinter program of pop new windows to do something.when I ran it,there are two problems.The first problem is poping two windows when click "1、reset chanel".I checked over and over,but the problem is still over there.The second problem is about the 'Entry' value.I want it to show the askdirectory value.Whatever I done,it is still empty.
Here is the code,any help is appreciated.
import tkinter as tk
from tkinter import filedialog, dialog
from tkinter.filedialog import askdirectory
from tkinter.messagebox import *
class SgyChan(tk.Toplevel):
def __init__(self):
super().__init__()
self.setup_UI()
def open_bigspsfile(self):
self.filebig_path = filedialog.askopenfilename()
self.bigpath.set(self.filebig_path)
print(self.filebig_path)
def open_litspsfile(self):
self.filelit_path = askdirectory() #
self.litpath.set(self.filelit_path)
print(self.filelit_path)
def getValueBig(self):
self.filebig_path=self.entry1.get()
return self.filebig_path
def getValueLit(self):
self.filelit_path=self.entry2.get()
return self.filelit_path
def mat_file(self):
spspath=self.getValueBig()
watchdir=self.getValueLit()
print('working......')
def setup_UI(self):
root = tk.Tk()
root.geometry('500x100+600+300')
root.title('sgy change chan')
self.bigpath= tk.StringVar()
self.litpath= tk.StringVar()
label1 = tk.Label(root, text="1、sps file:")
label2 = tk.Label(root, text="2、sgy :")
label1.grid(row=0)
label2.grid(row=1)
self.entry1 = tk.Entry(root,width=40,textvariable = self.bigpath)
self.entry2 = tk.Entry(root, width=40,textvariable = self.litpath)
self.entry1.grid(row=0, column=1)
self.entry2.grid(row=1, column=1)
buttonForFile = tk.Button(root, text="browser files", command=self.open_bigspsfile)
buttonRun = tk.Button(root, text="browser directory", command=self.open_litspsfile)
buttonForFile.grid(row=0, column=2)
buttonRun.grid(row=1, column=2)
buttonMatch = tk.Button(root, text="3、data process", command=self.mat_file)
buttonMatch.grid(row=4, column=1)
class MyApp(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('500x145+400+100')
self.title('sgy tools')
self.setupUI()
def setupUI(self):
row1 = tk.Frame(self)
row1.pack(fill="x")
buttonForFile = tk.Button(row1, text="1、reset chanel", command=SgyChan)
buttonForFile.grid(row=0, column=2)
if __name__ == '__main__':
app = MyApp()
app.mainloop()
Related
we are supposed to make a login screen my issue is that I am not familiar with top level windows and I dont know how to put labels and buttons on it
This is the code that I am working with
import tkinter as tk
from tkinter import ttk
import ttkthemes as th
class App(th.ThemedTk):
def __init__(self, title: str):
super().__init__()
self.title(title)
self.style = ttk.Style(self)
self.config(theme="adapta")
self.hello_label = ttk.Label(self, text="Hello, World!")
self.change_button = ttk.Button(self, text="Click Me", command=self.change_text)
self.window = tk.Label(self,text="New Window")
self.window = tk.Button(self, text="Click Me", command=self.change_text)
self.initialize_widgets()
def initialize_widgets(self):
self.hello_label.pack()
self.change_button.pack()
def change_text(self):
self.hello_label.config(text="I Changed!")
self.window = tk.Toplevel(self)
if __name__ == "__main__":
app = App("Login")
app.mainloop()
I though that I could type labels and commands under the init function but assign them to tk instead of ttk but it did not work
You need to assign the Label and Button to the new Toplevel that you create in change_text. The first argument in the widget creation functions is the parent widget. The change_text method below is amended to open a new Toplevel window and add the Label and Button to it.
import tkinter as tk
from tkinter import ttk
class App( tk.Tk ):
def __init__(self, title: str):
super().__init__()
self.title(title)
self.hello_label = ttk.Label(self, text="Hello, World!")
self.change_button = ttk.Button(self, text="Click Me", command=self.change_text)
# Moved into change_text.
# self.window = tk.Label(self,text="New Window")
# self.window = tk.Button(self, text="Click Me", command=self.change_text)
self.initialize_widgets()
def initialize_widgets(self):
self.hello_label.pack()
self.change_button.pack()
def change_text_tl( self ):
self.tl_label.config( text = 'Now I changed too!')
def change_text(self):
self.hello_label.config(text="I Changed!")
self.window = tk.Toplevel(self)
# parent kwargs ->
self.tl_label = tk.Label( self.window, text="New Window")
self.tl_button = tk.Button( self.window, text="Click Me",
command=self.change_text_tl)
self.tl_label.pack()
self.tl_button.pack()
if __name__ == "__main__":
app = App("Login")
app.mainloop()
My problem is, that then i open a second window with a button in the first window, the spinbox in the second window does not give an output. If i start the second one individually, it works as expectet. I used the pygub designer to design the windows.
Here is my Code from the first (main) window:
import tkinter.ttk as ttk
from tkinter import messagebox
import Test2
class NewprojectApp:
def __init__(self, master=None):
# build ui
toplevel1 = tk.Tk() if master is None else tk.Toplevel(master)
toplevel1.configure(height=500, width=500)
entry1 = ttk.Entry(toplevel1)
self.Entrytest1 = tk.StringVar()
entry1.configure(textvariable=self.Entrytest1)
entry1.pack(padx=10, pady=10, side="top")
spinbox1 = ttk.Spinbox(toplevel1)
self.Spinbox1 = tk.IntVar()
spinbox1.configure(from_=0, increment=1, textvariable=self.Spinbox1, to=10)
spinbox1.pack(padx=10, pady=10, side="top")
button2 = ttk.Button(toplevel1)
button2.configure(text="Neuesfenster")
button2.pack(padx=10, pady=10, side="top")
button2.bind("<ButtonPress>", self.ereignisbehandler, add="")
# Main widget
self.mainwindow = toplevel1
def run(self):
self.mainwindow.mainloop()
def ereignisbehandler(self, event=None):
messagebox.showinfo("Test", self.Spinbox1.get())
Test2.secondwindow()
if __name__ == "__main__":
app = NewprojectApp()
app.run()
And the second window:
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
class NewprojectApp2:
def __init__(self, master=None):
# build ui
toplevel2 = tk.Tk() if master is None else tk.Toplevel(master)
toplevel2.configure(height=500, width=500)
entry2 = ttk.Entry(toplevel2)
self.Entrytest1 = tk.StringVar()
entry2.configure(textvariable=self.Entrytest1)
entry2.pack(padx=10, pady=10, side="top")
spinbox2 = ttk.Spinbox(toplevel2)
self.Spinbox2 = tk.IntVar()
spinbox2.configure(from_=0, increment=1, state="normal", textvariable=self.Spinbox2, to=10)
spinbox2.pack(padx=10, pady=10, side="top")
button4 = ttk.Button(toplevel2)
button4.configure(text="Neuesfenster")
button4.pack(padx=10, pady=10, side="top")
button4.bind("<ButtonPress>", self.ereignisbehandler, add="")
# Main widget
self.mainwindow = toplevel2
def run(self):
self.mainwindow.mainloop()
def ereignisbehandler(self, event=None):
messagebox.showinfo("Test", self.Spinbox2.get())
if __name__ == "__main__":
app = NewprojectApp2()
app.run()
def secondwindow():
app = NewprojectApp2()
app.run()
Thank you for helping!
I have several simpledialog popup windows. The first one that shows is in focus and after it closes then every single one after that is not in focus. The simpledialog code is this:
from tkinter import *
from tkinter import messagebox
import os
import tkinter as tk
from tkinter import simpledialog
def doing_stocks():
name = myaskstring("Input data", "Enter box number:", parent = root)
name2 = myaskstring("Input data2", "Enter box number2:", parent = root)
name3 = myaskstring("Input data3", "Enter box number3:", parent = root)
class My_QueryString(tk.simpledialog._QueryString):
def body(self, master):
self.bind('<KP_Enter>', self.ok)
self.bind('<Return>', self.ok)
w = Label(master, text=self.prompt, justify=LEFT)
w.grid(row=0, padx=5, sticky=W)
self.entry = Entry(master, name="entry")
self.entry.grid(row=1, padx=5, sticky=W+E)
if self.initialvalue is not None:
self.entry.insert(0, self.initialvalue)
self.entry.select_range(0, END)
root.update_idletasks()
self.entry.focus_force()
return self.entry
def myaskstring(title, prompt, **kw):
d = My_QueryString(title, prompt, **kw)
root.update_idletasks()
answer = d.result
d.destroy()
return answer
root = Tk()
root.geometry("700x761")
label1 = Label(root, text="")
label1.place(x = 0, y = 0)
button2 = Button(root, text = "Doing Stocks", command=doing_stocks).place(x = 300, y = 340)
root.mainloop()
This is a simplified version of the code. I call my simpledialog popups like this:
myaskstring("Title", "Prompt", parent = root)
In the doing_stocks() method the first time I call myaskstring the window and the entry field will be in focus then all times after that it won't be. How can I make every simpledialog be in focus when it appears on the screen?
I agree is seems odd that the focus isn't set to each My_QueryString instance when it's initialized. Regardless of the reason why, a workaround for it not happening is to bind a <Map> event handler function to the dialog's Entry widget to shift keyboard focus to itself whenever it's made visible.
The code below shows an implementation doing that. It's based on your code with the important changes indicated with # ALL CAP comments to make them stand out.
import tkinter as tk
from tkinter import simpledialog
from tkinter.constants import *
def doing_stocks():
name = myaskstring("Input data", "Enter box number:", parent=root)
name2 = myaskstring("Input data2", "Enter box number2:", parent=root)
name3 = myaskstring("Input data3", "Enter box number3:", parent=root)
class My_QueryString(tk.simpledialog._QueryString):
def body(self, master):
self.bind('<KP_Enter>', self.ok)
self.bind('<Return>', self.ok)
w = tk.Label(master, text=self.prompt, justify=LEFT)
w.grid(row=0, padx=5, sticky=W)
self.entry = tk.Entry(master, name="entry")
self.entry.grid(row=1, padx=5, sticky=W+E)
self.entry.bind('<Map>', self.on_map) # <--- ADDED.
if self.initialvalue is not None:
self.entry.insert(0, self.initialvalue)
self.entry.select_range(0, END)
root.update_idletasks()
# self.entry.focus_force() # <--- NOT NEEDED.
return self.entry
# ADDED METHOD.
def on_map(self, event):
self.entry.focus_force()
def myaskstring(title, prompt, **kw):
d = My_QueryString(title, prompt, **kw)
root.update_idletasks()
answer = d.result
# d.destroy() # <--- NOT NEEDED.
return answer
root = tk.Tk()
root.geometry("700x761")
label1 = tk.Label(root, text="")
label1.place(x = 0, y = 0)
button2 = tk.Button(root, text = "Doing Stocks", command=doing_stocks)
button2.place(x = 300, y = 340)
root.mainloop()
So basically i want to make this GUI where you can insert text and then hit the go button ad it would do the feature. (example: "Stopwatch" and then after you hit enter it would start a stopwatch).
import tkinter as tk
import math
import time
root = tk.Tk()
root.geometry()
root.attributes("-fullscreen", True)
exit_button = tk.Button(root, text = "Exit", command = root.destroy)
exit_button.place(x=1506, y=0)
main_entry = root.Entry(root, )
root.mainloop()
So basically I want the answer in main entry to be taken and do the action asked in the text insertion.
Here i wrote an example on how to use the Entry and the Button widgets in Tkitner:
from tkinter import *
from tkinter.messagebox import showerror
import random
class App(Tk):
def __init__(self):
super(App, self).__init__()
self.title('Get a random integer')
self.geometry('400x250')
Label(self, text='Get a random number from A to B').pack(pady=20)
self.a_value = Entry(self, width=10)
self.a_value.insert(END, 'A')
self.a_value.pack(pady=5)
self.b_value = Entry(self, width=10)
self.b_value.insert(END, 'B')
self.b_value.pack(pady=5)
self.btn = Button(self, text='Get Random', command=self.get_rand)
self.btn.pack(pady=5)
self.out_label = Label(self)
self.out_label.pack(pady=10)
self.bind('<Return>', self.get_rand)
def get_rand(self, event=None):
a = self.a_value.get()
b = self.b_value.get()
try:
a = int(a)
b = int(b)
self.out_label.configure(text=f'{random.randint(a, b)}')
self.update()
except Exception as error:
showerror(title='ERROR', message=f'{error}')
if __name__ == '__main__':
myapp = App()
myapp.mainloop()
I have created an coding gui,which doesnot show 'File' and 'save' in the Gui
Please help me to fix my problem.
I have created a Function for File and Save ,still not working!
please help me to rectify my code!
from tkinter import *
import tkinter.messagebox
import tkinter
import tkinter as tki
import tkinter.filedialog as th1
import re
class App(object):
def __init__(self,root):
self.root = root
# create a Frame for the Text and Scrollbar
txt_frm = tki.Frame(self.root, width=600, height=400)
txt_frm.pack(fill="both", expand=True)
# ensure a consistent GUI size
txt_frm.grid_propagate(False)
# create first Text label, widget and scrollbar
self.lbl1 = tki.Label(txt_frm, text="Type")
self.lbl1.grid(row=0,column=0,padx=2,pady=2)
self.txt1 = tki.Text(txt_frm, borderwidth=3, relief="sunken", height=4,width=55)
self.txt1.config(font=("consolas", 12), undo=True, wrap='word')
self.txt1.grid(row=0, column=1, sticky="nsew", padx=2, pady=2)
scrollb1 = tki.Scrollbar(txt_frm, command=self.txt1.yview)
scrollb1.grid(row=0, column=2, sticky='nsew')
self.txt1['yscrollcommand'] = scrollb1.set
button = tki.Button(txt_frm,text="Clickone", command = self.retrieve_input)
button.grid(column=2,row=0)
button1 = tki.Button(txt_frm,text="Cli", command = self.clearBox)
button1.grid(column=2,row=0)
def retrieve_input(self):
input1 = self.txt1.get("0.0",'end-1c')
with open('text.txt','a+') as f:
f.write(input1+'\n')
f.close()
def clearBox(self):
self.txt1.delete('1.0', 'end')#<-0.0/1.0
def file_save():
f = th1.asksaveasfile(mode='w', defaultextension=".txt")
if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
return
text2save = str(text.get(1.0, END))
a= (f)
f.write(text2save)
f.close()
root = tki.Tk()
menubar=Menu(root)
filemenu=Menu(menubar,tearoff=0)
filemenu.add_command(label="Save", command=file_save)
app = App(root)
root.mainloop()
Please help!Answers will be appreciated!
You aren't adding the menubar to the window. Add this after you create the menubar.
root.configure(menu=menubar)
You then also have to add the file menu to the menubar:
menubar.add_cascade(label="File", menu=filemenu)