我已经编写了我的第一个 wxpython 应用程序,它运行良好,但我遇到了正确调整主窗口大小的困难。该面板包含一个wx.BoxSizer
,而后者又包含一个wx.FlexGridSizer
,而后者又包含 6 个wx.TextCtrl
s。
我读过的教程似乎侧重于手动设置大小。我真正想做的是让TextCtrl
s 计算出它们应该是什么大小以包含来自给定字体的 3 个字符(比如“WWW”),然后应该自动确定 FlexGridSizer 的大小和主窗户。我不需要担心调整布局的大小(所以也许 Sizer 不是必需的?),我只想自动确定大小,而不是通过我将魔术常量放入程序中。
import wx
from names_as_vs import name_sum, name_mult
NAME_SIZE = 35
class MyForm(wx.Frame):
def __init__(self, parent,title):
wx.Frame.__init__(self,parent,title=title,size=(405,200))
self.default_init_UI()
self.init_UI()
self.Show()
def default_init_UI(self):
"""Do all the standard UI stuff"""
file_menu = wx.Menu()
menuAbout = file_menu.Append(wx.ID_ABOUT,"About\tCtrl-A")
menuExit = file_menu.Append(wx.ID_EXIT,"Quit\tCtrl-Q")
menu_bar = wx.MenuBar()
menu_bar.Append(file_menu,"File")
self.SetMenuBar(menu_bar)
self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
def init_UI(self):
"""Particular UI setup for this program"""
hbox = wx.BoxSizer(wx.HORIZONTAL)
panel = wx.Panel(self)
fgs = wx.FlexGridSizer(2,5,9,9)
fixed_elts_args = {"size":(30,70)}
plus = wx.StaticText(panel, label="+", **fixed_elts_args)
times = wx.StaticText(panel, label=".",**fixed_elts_args)
equals1 = wx.Button(panel, label="=", **fixed_elts_args)
equals2 = wx.Button(panel, label="=", **fixed_elts_args)
equals1.Bind(wx.EVT_BUTTON, self.compute_sum)
equals2.Bind(wx.EVT_BUTTON, self.compute_mult)
font = wx.Font(48,wx.ROMAN,wx.NORMAL,wx.NORMAL)
text_ctrl_args = {"size":(95,70)}
self.summand1 = wx.TextCtrl(panel, **text_ctrl_args)
self.summand2 = wx.TextCtrl(panel, **text_ctrl_args)
self.scalar = wx.TextCtrl(panel, **text_ctrl_args)
self.multiplicand = wx.TextCtrl(panel, **text_ctrl_args)
self.sum_result = wx.TextCtrl(panel, style = wx.TE_READONLY, **text_ctrl_args)
self.mult_result = wx.TextCtrl(panel, style = wx.TE_READONLY, **text_ctrl_args)
for ctrl in (plus,times,equals1,equals2,self.summand1,self.summand2,
self.scalar,self.multiplicand,self.sum_result,self.mult_result):
ctrl.SetFont(font)
fgs.AddMany([
self.summand1,plus,self.summand2,equals1,self.sum_result,
self.scalar,times,self.multiplicand,equals2,self.mult_result
])
hbox.Add(fgs, proportion=1, flag= wx.ALL, border=15)
panel.SetSizer(hbox)
def OnAbout(self,e):
dlg = wx.MessageDialog(self, "A GUI implementation of 815 as a vector space", "About 815 as a vector space", wx.OK)
dlg.ShowModal() # Shows it
dlg.Destroy() # finally destroy it when finished.
def OnExit(self,e):
self.Close(True) # Close the frame.
def compute_sum(self,e):
"""Computes the sum of the names in summand1 and summand2 and displays the result in self.sum_result"""
n1 = self.summand1.GetValue()
n2 = self.summand2.GetValue()
self.sum_result.SetValue(name_sum(n1,n2))
def compute_mult(self,e):
"""
Computes the scalar multiple of the name in multiplicand by the scalar in scalar and displays the result in self.mult_result
"""
n = self.multiplicand.GetValue()
lamb = self.scalar.GetValue()
self.mult_result.SetValue(name_mult(lamb,n))