I need a separate frame, same as Python idle on tkinter window - python

I tried a lot to embedded the python idlw with my tkinter window. Is there any predefined module to embed idle with tkinter window?
# -*- coding: utf-8 -*-
## Front Homepage
from sklearn import linear_model
import matplotlib.pyplot as plt
from matplotlib import interactive
from login import *
from PIL import ImageTk, Image
import tkinter as tk
import os
from tkinter.ttk import *
##creating window
root = tk.Tk()
## Title bar of front page
program_name="Silk Project : SUPERVISED MODEL"
root.title(program_name)
root.configure(bg = "Pink")
## Menu Bar
menu_bar=Menu(root)
## File menu in menu bar
file_menu=Menu(menu_bar,tearoff=0)
menu_bar.add_cascade(label="File",menu=file_menu,underline=0)
file_menu.add_command(label="New",accelerator="Ctrl+N")
file_menu.add_command(label="Open",accelerator="Ctrl+O")
file_menu.add_command(label="Save",accelerator="Ctrl+S")
file_menu.add_command(label="Save as",accelerator="Shift+Ctrl+S")
file_menu.add_separator()
file_menu.add_command(label="Exit",accelerator="Alt+F4",)
root.config(menu=menu_bar)
## Edit menu in menu bar
Edit_menu=Menu(menu_bar,tearoff=0)
menu_bar.add_cascade(label="Edit",menu=file_menu,underline=0)
Edit_menu.add_command(label="New",accelerator="Ctrl+N")
Edit_menu.add_command(label="Open",accelerator="Ctrl+O")
Edit_menu.add_command(label="Save",accelerator="Ctrl+S")
Edit_menu.add_command(label="Save as",accelerator="Shift+Ctrl+S")
Edit_menu.add_separator()
Edit_menu.add_command(label="Exit",accelerator="Alt+F4",)
root.config(menu=menu_bar)
## Option menu in menu bar
Option_menu=Menu(menu_bar,tearoff=0)
menu_bar.add_cascade(label="Option",menu=file_menu,underline=0)
Option_menu.add_command(label="New",accelerator="Ctrl+N")
Option_menu.add_command(label="Open",accelerator="Ctrl+O")
Option_menu.add_command(label="Save",accelerator="Ctrl+S")
Option_menu.add_command(label="Save as",accelerator="Shift+Ctrl+S")
Option_menu.add_separator()
Option_menu.add_command(label="Exit",accelerator="Alt+F4",)
root.config(menu=menu_bar)
## FrAME A
s = Style()
s.configure('My.TFrame', background='plum1')
frame = Frame(root , style='My.TFrame')
frame.place(height=600, width=250, x=0, y=0)
## FrAME B
s1 = Style()
s1.configure('My2.TFrame', background='White')
frame2 = Frame(root , style='My2.TFrame')
frame2.place(height=590, width=950, x=250, y=15)
##Output Label
var="Output"
label1 = tk.Label(root , borderwidth = 10 , text=var , background="orange")
label1.place(height =15 , width =50 ,x=250,y=0)
## Size of Homepage
root.geometry("1200x600+50+25")
#not minimization and maximization property
root.resizable(0,0)
## Output Window :
from tkinter import *
from subprocess import *
print("Hello world")
def func():
proc = Popen("run.py", stdout=PIPE, stdin=PIPE ,stderr=PIPE , shell=True)
proc = proc.communicate()
output.insert(END, proc)
Check = Button(frame, text="Display output", command=func)
Quit = Button(frame, text="Exit", fg="red", command=root.quit)
output = Text(frame2)
Check.pack()
Quit.pack()
output.place(height=590, width=950, x=0, y=0)
root.iconbitmap(r'C:\Users\Silk\Desktop\SILK\SILK-GUI\5.ico')
root.mainloop()

No. IDLE is an application written in Python that uses tkinter. There are a few components that one might use in other applications, and might be more in the future, but they are subject to change and exernal use is not officially supported.

Related

Frame in Tkinter Popup Putting Content into Main Window instead of Popup

I am trying to create an app using the Tkinter Python library, and I created a preferences popup. I want to add checkboxes to it, and I want to do it in Frames via pack().
I want something like this:
Expected Result (IK it's Edited but Proof of Concept)
This is what I'm getting:
Actual Result (Look at Bottom of Image)
This is what I wrote:
# Import Libraries
from tkinter import *
from tkinter import ttk
from tkinter import simpledialog, messagebox
from tkinter.filedialog import asksaveasfile
from pygame import mixer as playsound
from datetime import datetime as date
from time import sleep
import pyttsx3
import json
import os
# Set Initial Window
window = Tk()
window.title("TTSApp")
window.geometry('500x580')
window.resizable(width=False,height=False)
playsound.init()
# Settings and Menu
preferences = {}
def preferencesHandler():
if os.path.exists('preferences.pref'):
preferences = {'AutoSave':True,'AutoSavePrompt':True,'AutoSaveAutomaticLoad':False}
with open('preferences.pref', 'w') as pref:
json.dump(preferences, pref)
else:
preferences = json.load(open('preferences.pref', 'r'))
pref.close()
sessionOptions = {'SessionName':'Untitled','VoiceSpeed':100}
def topmenucommands_file_newsession():
messagebox.showerror("New Session", "I haven't done this yet... you shouldn't even be able to see this...")
def topmenucommands_file_preferences():
preferencesWin = Toplevel(window)
preferencesWin.geometry("350x500")
preferencesWin.title("Preferences")
preferences_autosave = BooleanVar()
preferences_autosaveprompt = BooleanVar()
preferences_autosaveautomaticload = BooleanVar()
def topmenucommands_file_preferences_changed(*args):
with open('preferences.pref') as pref:
preferences['AutoSave'] = preferences_autosave.get()
preferences['AutoSavePrompt'] = preferences_autosaveprompt.get()
preferences['AutoSaveAutomaticLoad'] = preferences_autosaveautomaticload.get()
json.dump(preferences, pref)
pref.close()
Label(preferencesWin, text="Preferences", font=('helvetica', 24, 'bold')).pack()
autosave_container = Frame(preferencesWin,width=350).pack()
Label(autosave_container, text="Create Autosaves:", font=('helvetica', 12, 'bold')).pack(side=LEFT)
ttk.Checkbutton(autosave_container,command=topmenucommands_file_preferences_changed,variable=preferences_autosave,onvalue=True,offvalue=False).pack(side=RIGHT)
window.wait_window(preferencesWin)
pref.close()
def topmenucommands_session_renamesession():
topmenucommands_session_renamesession_value = simpledialog.askstring(title="Rename Session",prompt="New Session Name:")
sessionOptions['SessionName'] = topmenucommands_session_renamesession_value
topmenu = Menu(window)
topmenu_file = Menu(topmenu, tearoff=0)
#topmenu_file.add_command(label="New Session")
#topmenu_file.add_command(label="Save Session")
#topmenu_file.add_command(label="Save Session As...")
topmenu_file.add_command(label="Preferences", command=topmenucommands_file_preferences)
topmenu.add_cascade(label="File", menu=topmenu_file)
topmenu_session = Menu(topmenu, tearoff=0)
topmenu_session.add_command(label="Rename Session", command=topmenucommands_session_renamesession)
topmenu.add_cascade(label="Session", menu=topmenu_session)
# Create All of the Widgets and Buttons and Kiknacks and Whatnot
# Input Window
inputText = Text(window,height=20,width=62)
inputText.pack()
# Label for Speed Slider
speedText = Label(window, text='Voice Speed', fg='black', font=('helvetica', 8, 'bold'))
speedText.pack()
# Speed Slider
speed = Scale(window, from_=50, to=200, length=250, tickinterval=25, orient=HORIZONTAL, command=speedslidersavestate)
speed.set(100)
speed.pack()
# Dropdown for Voice Selection
voice = OptionMenu(window, voiceSelection, *voiceNames.keys())
voice.pack()
# Warning/Notice Label
warning = Label(window, text='', fg='red', font=('helvetica', 12, 'bold'))
warning.pack()
# Container for All Preview and Save (and PreviewRaw)
buttons = Frame(window)
buttons.pack()
# PreviewRaw Button; Huh... There's Nothing Here
# Preview Button
preview = Button(buttons,text='Preview',height=5,width=25,command=preview)
preview.pack(side=LEFT)
# Save Button
save = Button(buttons,text='Save to File',height=5,width=25,command=save)
save.pack(side=RIGHT)
window.config(menu=topmenu)
preferencesHandler()
window.mainloop()
Did I do something wrong or is there a better way to go about this or is this question a mess (this is my first time doing this)? Also, I clipped out all of the unnecessary content.
Edit: Added More Code
I figured it out. Apparently, I needed to pack() the Frame separately.
The answer was:
autosave_container = Frame(preferencesWin,width=350)
autosave_container.pack()
Instead of:
autosave_container = Frame(preferencesWin,width=350).pack()

Treeview moves after click on Combobox with Tkinter

I have developped a app in Python (tested with 3.8 and 3.9 on Windows 10) with Tkinter. I am using a Combobox and a Treeview. I want to change dynamically the width of dropdown listbox and I could do it by changing the style of TCombobox with the parameter postoffset.
However, everytime I click on the Combobox, the table next to it moves and extends its width by itself. I really don't know where this problem comes from.
I have created a simple code so that you can reproduce the problem.
import tkinter as tk
from tkinter import ttk
import tkinter.font as tkfont
def combo_configure(event, style):
combo = event.widget
long = max(combo.cget('values'), key=len)
font = tkfont.Font(family="Helvetica", size=10)
width = max(0,font.measure(long.strip() + '0') - combo.winfo_width())
style.configure('TCombobox', postoffset=(0,0,width,0))
win = tk.Tk()
win.geometry("850x250")
style = ttk.Style()
f = tk.Frame(win)
f.configure(bg="black")
f.pack()
combo = ttk.Combobox(f, style="TCombobox", values=["It's a test on Combobox style."], width=10)
combo.bind('<ButtonPress>', lambda e : combo_configure(e, style))
combo.pack(side="left")
tree = ttk.Treeview(f, column=["Column 1"], show='headings', height=10)
tree.heading(0, text="Column 1")
tree.column(0, anchor=tk.CENTER, width=125)
tree.pack()
win.mainloop()
Thanks.

Tkinter creating two windows instead of one

I have created this tkinter widget, but when I run the code I get a MainWindow and a window that is labeled tk when I only want the one (MainWindow).
from tkinter import *
from tkinter.ttk import *
import backend
def Sll_command():
row = backend.straightLineLink()
print(row)
style = Style()
style.configure('W.TButton', front =('calibri', 10,
'bold', 'underline'), foreground = 'red')
window = Tk()
window.wm_title("MainWindow")
window.resizable(width=True , height=True)
Grid.rowconfigure(window,0,weight=1)
Grid.columnconfigure(window, 0, weight=1)
b1 = Button(window, text = "SLL",
style = 'W.TButton',
command=Sll_command,)
b1.grid(row=2,column=5)
window.mainloop()

Tkinter MessageBox 'pausing' main GUI [duplicate]

I've found that when a toplevel widget calls a messagebox dialog (like "showinfo"), the root window is showed up, over the toplevel. Is there a way to set the Toplevel window as the master of the messagebox dialog ?
Here is a script to reproduce this :
# -*- coding:utf-8 -*-
# PYTHON 3 ONLY
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title('ROOT WINDOW')
Label(root, text = 'Place the toplevel window over the root window\nThen, push the button and you will see that the root window is again over the toplevel').grid()
topWindow = Toplevel(root)
topWindow.title('TOPLEVEL WINDOW')
Label(topWindow, text = 'This button will open a messagebox but will\ndo a "focus_force()" thing on the root window').grid()
Button(topWindow, text = '[Push me !]', command = lambda: messagebox.showinfo('foo', 'bar!')).grid()
# --
root.mainloop()
You can set the parent argument to topWindow for the showInfo command:
Button(..., command=lambda: messagebox.showInfo(parent=topWindow, ...))
See also:
http://effbot.org/tkinterbook/tkinter-standard-dialogs.htm
This may address more current versions.
#TEST AREA forcommands/methods/options/attributes
#standard set up header code 2
from tkinter import *
from tkinter import messagebox
root = Tk()
root.attributes('-fullscreen', True)
root.configure(background='white')
scrW = root.winfo_screenwidth()
scrH = root.winfo_screenheight()
workwindow = str(1024) + "x" + str(768)+ "+" +str(int((scrW-1024)/2)) + "+" +str(int((scrH-768)/2))
top1 = Toplevel(root, bg="light blue")
top1.geometry(workwindow)
top1.title("Top 1 - Workwindow")
top1.attributes("-topmost", 1) # make sure top1 is on top to start
root.update() # but don't leave it locked in place
top1.attributes("-topmost", 0) # in case you use lower or lift
#exit button - note: uses grid
b3=Button(root, text="Egress", command=root.destroy)
b3.grid(row=0,column=0,ipadx=10, ipady=10, pady=5, padx=5, sticky = W+N)
#____________________________
root.withdraw()
mb1=messagebox.askquestion(top1, "Pay attention: \nThis is the message?")
messagebox.showinfo("Say Hello", "Hello World")
root.deiconify()
top1.lift(aboveThis=None)
#____________________________
root.mainloop()
Button(..., command=lambda: messagebox.showinfo("The Title", "A piece of text", parent=topWindow))
This will definitely work. The syntax of the messagebox is
messagebox.Function_Name(title, message [, options])
setting the parent argument is one of the options
add topWindow.attributes("-topmost", 1)
after defining the Toplevel, and this should fix the problem

Anti-aliased fonts in tkinter?

Is there a way to get anti-aliased fonts in tkinter? If I increase the size of the default font like so:
default_font = tkFont.nametofont("TkDefaultFont")
default_font.configure(size=32)
the text comes out jagged.
Here is some version information:
Python 2.7.9 (default, May 6 2015, 09:33:48)
>>> Tkinter.__version__
'$Revision: 81008 $
I am using Gentoo Linux and have Tk 8.5 installed (which i believe should support anti-aliased fonts):
$ equery l tk
[IP-] [ ] dev-lang/tk-8.5.17:0/8.5
EDIT: adding this full MWE to describe what I'm doing:
from Tkinter import *
import tkFont
from ttk import *
root = Tk()
note = Notebook(root)
default_font = tkFont.nametofont("TkDefaultFont")
default_font.configure(size=48)
tab1 = Frame(note)
tab2 = Frame(note)
Button(tab1, text='Exit', command=root.destroy).pack(padx=100, pady=100)
note.add(tab1, text = "Curvy Words")
note.add(tab2, text = "Aliased")
note.pack()
root.mainloop()
exit()
It turns out to have been an issue with how tk was installed with gentoo. After adding truetype support by setting the use flag
For example, I added the line to /etc/portage/package.use
>=dev-lang/tk-8.5.17 truetype
And then remerged tk:
emerge -Na tk
I don't know much about ttk, but do know that you use "style" to set the font-->ttk tutorial http://www.tkdocs.com/tutorial/styles.html This looks fine on my Slackware box, but it uses anti-aliased by default.
from Tkinter import *
import ttk
import tkFont
root = Tk()
##default_font = tkFont.nametofont("TkDefaultFont")
##default_font.configure(size=48)
f = tkFont.Font(family='helvetica', size=24)
s = ttk.Style()
s.configure('.', font=f)
note = ttk.Notebook(root)
tab1 = ttk.Frame(note)
tab2 = ttk.Frame(note)
note.add(tab1, text = "Curvy Words")
note.add(tab2, text = "Aliased")
note.pack()
ttk.Style().configure("TButton", padding=6, relief="flat",
background="white")
ttk.Button(tab1, text='Exit', command=root.destroy).pack(padx=100, pady=100)
root.mainloop()

Categories